1.可以把getter理解成store.js的计算属性
- 在store.js中定义常量getters,添加一个属性count1
const getters={
count1:function(state){
return state.count+=100;
}
}
- 同样作为store的属性暴露出去
export default new Vue.store({
state,
getters
})
- 在组件的计算属性中获取
methods:{
count1:function(){
return this.store.getters.count1;}
}
2.state和mutation都有相应的map引用方法对模板中的编码进行简化,getter也有。
- 首先引入mapGetters
import {mapGetters} from 'Vuex'
- 使用对象符将getter混入computed对象中
当getters中的属性和组件节点的属性相同时可以通过mapGetters辅助函数的数组参数来赋值
computer:{
...mapGetters(['count1'])
}
如果想将一个getter属性另取一个名字,使用对象形式:
computer:{
...mapGetters({
count3:'count1'
})
}
- $refs的基本用法
<div id="app">
<input type="text" ref="input1"/>
<button @click="add">添加<button>
</div>
<script>
new Vue({
el:"#app",
methods:{
add:function(){
this.$refs.input1.value="22" // this.$refs.input1减少获取dom节点的消耗
}
}
})
</script>
一般来讲,获取dom元素,需要document.querySelector(".input1")获取这个dom节点,然后再获取input1的值。但是用ref绑定后,我们就不需要再获取dom节点了,直接在上面的input上绑定input1,然后$refs里调用就行。