一、常用指令
注:不推荐同时使用 v-if
和 v-for
,当 v-if
与 v-for
一起使用时,v-for
具有比 v-if
更高的优先级。
1、v-for
的使用:
格式: v-for="item in items"
或者v-for="(item,index) in items"
,如:
<ul id="example-1">
<li v-for="item in items" :key="item.message">
{{ item.message }}
</li>
</ul>
若:v-for
遍历的是一个对象,则第一个参数为属性值,第二个参数为属性名,第三个参数为下标,如:
<div v-for="(value, name, index) in object">
{{ index }}. {{ name }}: {{ value }}
</div>
注:当在组件上使用 v-for 时,key 现在是必须的。
2、v-on
:可以用来监听 DOM 事件:
<div id="example-2">
<!-- `greet` 是在下面定义的方法名 -->
<button v-on:click="greet">Greet</button>
</div>
也可写为:此时采用@缩写,并向greet函数传递一个参数啊
<div id="example-2">
<button @click="greet(a)">Greet</button>
</div>
即:v-on可缩写为@。
3、v-model
:用在表单控件上的,用于实现双向数据绑
二、路由部分
1、路由的使用(一定要加占位符)- 在需跳转的页面配置如下:
<router-link to="/">...</router-link>
并且在主页面加上占位符:<router-view/>
- 占位符顾名思义,就是跳转的页面所放置的位置
- 在router文件的index.js中,配置需要跳转的到的页面:
其中,path的值需要与上一张图中to的值一一对应;component的值表示,一旦有访问path这个路径,则展示这个页面。
此外需注意:要将对应页面引入到router的index.js文件中,如导入Home页面:import Home from '../views/Home.vue'
2、返回上一级路由
- 方法一:this.$router.go(-1)。
相对于当前页面向前或向后跳转多少个页面,跳转级数由参数决定。
- 方法二:
三、计算属性部分
一般情况下属性都是放到data中的,但是有些属性可能是需要经过一些逻辑计算后才能得出来,那么我们可以把这类属性变成计算属性。注:放到computed中的属性,不能再放到data中。
格式:
computed:{
属性名:function(){return xxx}
或:属性名(){return xxx}
}
举例:
computed:{
area(){
return this.width*this.height
}
}
四、vuex
1、state中存放的是数据
2、在其他页面可通过this.$store.state.变量名,来获得变量值。
3、mutations是定义改变state中数据改变的模块,在这个模块可通过方法去修改state中的数据。如:定义了一个addCount函数去修改state中的count变量。
mutations: {
// 改变state.cout的值
addCount(state){
state.count++;
}
},
4、this.$store.commit()
和this.$store.dispatch()
- commit 对应mutations, 用来触发同步操作的方法.
- dispatch对应actions, 用来触发异步操作的方法.
addNumber(){
this.$store.commit("addCount");
}
在自定义的addNumber方法中,通过this.$store.commit()调用
store文件中的addCount方法
各自的使用方法如下:
commit:
this.$store.commit('方法名',值) //传值时
this.$store.commit("方法名") //不传值
dispatch:
this.$store.dispatch('方法名',值) //传值时
this.$store.dispatch("方法名") //不传值