玩转Vue

31次阅读

共计 5057 个字符,预计需要花费 13 分钟才能阅读完成。

1 小时 Vue

Vue Tutorial in 2018 – Learn Vue.js by Example 的笔记,深入浅出,通俗易懂。

效果如下,在线演示地址:http://www.caishuxiang.cn/demo/190619vueproj/#/

安装 Vue

​ 安装 vue 有三种方式,本次使用 Vue CLI

Vue 提供了一个官方的 CLI,为单页面应用 (SPA) 快速搭建繁杂的脚手架。它为现代前端工作流提供了 batteries-included 的构建设置。只需要几分钟的时间就可以运行起来并带有热重载、保存时 lint 校验,以及生产环境可用的构建版本

​ 步骤:

  • 安装 vue cli

    > npm install -g @vue/cli
  • 开始一个新的 Vue 项目

    > vue create vue-proj
  • 进入项目,开启服务,访问 localhost:8080

    yarn serve

Vue 组件

​ 组件是组成 Vue 应用的基本单元,可以看下 vue-pro 的工程目录

​ 这里的 App.vue、Skill.vue 就是组件,每个 vue 文件都是组件。

组件的结构

  • template 中放置的是 html
  • script 中是页面的逻辑
  • style 中即样式信息
<template>
  ...
</template>

<script>
  ...
</script>

<style>
 ...
</style>

引入其他的组件

​ 如下所示:

<template>
  <!-- Other HTML removed for brevity -->
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  <!-- Other HTML removed for brevity -->
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'app',
  components: {HelloWorld}
}
</script>

Vue class 和 style 绑定

scoped

​ style 元素上使用了 scoped,那么该 style 下面的写的 css 或者引用的外部 css,只对所在 component 中的元素起作用. 如下:

<style scoped>

body {background-color: #eeeeee;}

</style>

如何引入外部 css 资源

注意:加了 scoped 代表该 css 只在当前 componet 中元素生效

<style src=”./Skills.css” scoped></style>

class 的绑定

<template>
  <div class="skills">
    <div class="holder">
    
      <!-- Add this -->
      <div v-bind:class="{alert: showAlert}"></div>

    </div>
  </div>
</template>
<script>
export default {
  name: 'Skills',
    data() {
        return {showAlert: true  // Add this}
      },
  }
}
</script>

如上,只有在 showAlert 为 true 时,才该 div 的 class 属性加上 alert 的值。

class 绑定多个值

<div v-bind:class="{alert: showAlert,'another-class': showClass}"></div>

style 绑定

<div v-bind:style="{backgroundColor: bgColor, width: bgWidth, height: bgHeight}"></div>
<script>
export default {
  name: 'Skills',
    data() {
        return {
          bgColor: 'yellow',
            bgWidth: '100%',
            bgHeight: '30px'
        }
      },
  }
}
</script>

为了模板中代码的简洁,你也可以如下写

<div v-bind:style="alertObject"></div>
<script>
export default {
  name: 'Skills',
    data() {
        return {
          alertObject:{
              backgroundColor: 'yellow',
                 width: '100%',
                 height: '30px'
          }
        }
      },
  }
}
</script>

Vue template

在 vue 的模板 <template></template> 里,可以写 html,和使用 vue 特定的功能。

vue 在模板里的功能分为两类:

  • vue interpolation(vue 的插入)文本插值用 {{}} 元素属性插入用 v -on v-bind 这些指令、也可以在{{}} 中写表达式
  • vue directives(vue 的指令)都是以 v - 开头的,每个指令都有自己的特定任务

下面的代码中. 有用到上述的两种功能

<template>
    <div class="skills">
       文本插入: {{name}}
        <h1 v-once>{{name}}</h1>
       插入表达式:{{btnState ? 'The button is disabled' : 'The button is active'}}
        元素属性插入:<button v-on:click="changeName" v-bind:disabled="btnState">Change Name</button>
        
        v-for 指令
        <ul>
            <li v-for="(data,index) in skills" :key='index'>{{index}}. {{data.skill}}</li>
        </ul>
        <p v-if="skills.length >= 1">you have >=1</p>
        <p v-else>you have 小于 1 </p>
     </div>
</template>

全部的 vue 指令如下

  • v-text
  • v-html
  • v-show
  • v-if
  • v-else
  • v-else-if
  • v-for
  • v-on
  • v-bind
  • v-model
  • v-pre
  • v-cloak
  • v-once

Vue 表单

v-model 的双向绑定

<!-- Add these two lines: -->
<input type="text" placeholder="Enter a skill you have.." v-model="skill">

{{skill}}

上述代码运行后:在输入框里输入,输入框后面的文本也会显示相应内容

如何导入验证的第三方插件

/src/main.js 文件中做如下更改

import Vue from 'vue'import App from './App.vue'

import VeeValidate from 'vee-validate'; // Add this
Vue.use(VeeValidate); // Add this

// Other code removed for brevity

验证的完整代码:

<form @submit.prevent="addSkill">
    <input type="text" placeholder="输入一个技能" v-model="skill" v-validate="'min:5'" name="skill">
    <p class="alert" v-if="errors.has('skill')">{{errors.first('skill')}}</p>
</form>
<script>
    export default {
        name: 'Skills',
        data: function() {
            return {
                skill: '',
                skills: [{"skill": "vue.js"},
                    {"skill": "php"}
                ]
            }
        },
        methods: {addSkill() {this.$validator.validateAll().then((result) => {if(result) {
                        this.skills.push({skill: this.skill});
                        this.skill = "";
                    } else {console.log("Not valid");
                    }
                })
            }
        }
    }
</script>

Vue 动画

vue2 中集成了进入离开动画、状态过渡效果

下面演示了一个进入离开动画写法,需要动画的元素被 <transition name=’value’></transition> 包裹,然后利用 value 值做 css 选择器的前缀,书写 css,如下:

<form @submit.prevent="addSkill">
    <input type="text" placeholder="Enter a skill you have.." v-model="skill" v-validate="'min:5'" name="skill" >
    <!-- Add these 3 lines -->
    <transition name="alert-in">
    <p class="alert" v-if="errors.has('skill')">{{errors.first('skill') }}</p>
    </transition>
</form>
<style>
.alert-in-enter-active {animation: bounce-in .5s;}
.alert-in-leave-active {animation: bounce-in .5s reverse;}
@keyframes bounce-in {
  0% {transform: scale(0);
  }
  50% {transform: scale(1.5);
  }
  100% {transform: scale(1);
  }
}
</style>

上面演示了 enter-activeleave-active两个类名,实际上 vue 提供了 6 中用于过渡中切换的类名。

  • v-enter
  • v-enter-active
  • v-enter-to
  • v-leave
  • v-leave-active
  • v-leave-to

对于这些在过渡中切换的类名来说,如果你使用一个没有名字的 <transition>,则 v- 是这些类名的默认前缀。如果你使用了 <transition name=”my-transition”>,那么 v-enter 会替换为 my-transition-enter。

vue 如何使用动画库

拿 Animate.css 举例,引入了 animate.css 之后,直接加 enter-active-class=”animated flipInx”

<transition name="alert-in" 
            enter-active-class="animated flipInX" 
            leave-active-class="animated flipOutX">
<p class="alert" 
   v-if="errors.has('skill')">{{errors.first('skill') }}</p>
</transition>

Vue 路由

vue 提供了 vue-router, 用于在 vue 组件中设置页面路径

  1. 安装 vue router

    > yarn add vue-router
  2. 新增 /src/router.js 配置路由:

    import Vue from 'vue'
    import Router from 'vue-router'
    import Skills from './components/Skills.vue'
    import About from './components/About.vue'
    Vue.use(Router)
    export default new Router({
      routes: [
        {
          path: '/',
          name: 'skills',
          component: Skills
        },
        {
          path: '/about',
          name: 'about',
          component: About
        }
      ]
    })
  3. main.js 中引入路由

    // other imports removed for brevity
    import router from './router'
    new Vue({
      router,               // Add this line
      render: h => h(App)
    }).$mount('#app')
    
    ## 在 App.vue 中运用路由
    <template>
      <div id="app">
          <nav>
            <router-link to="/">Home</router-link>
            <router-link to="/about">About</router-link>
          </nav>
        <router-view/>
      </div>
    </template>

最终的切换效果:

不妨在本地跑起来玩玩吧~ github 地址:https://github.com/pluscai/vue-proj

正文完
 0