vuex的state在组件选项data和computed上引用的区别

引用在vue组件的data选项,不因数值被改变而更新
引在在vue组件的computed选项,因数值变化而更组件

案例代码如下,调整下引用vue和vuex地址即可展示

 

<!DOCTYPE html>
<html>
<head>
  <title> vuex的配置state,mutations 和vue组件调用及模板组件</title>
  <script src="js/vue.js" type="text/javascript"></script>
  <script src="js/vuex.js" type="text/javascript"></script>

  <meta charset="utf-8"/>
</head>
<body>
	<div id="app">
		{{msg}}
		<!-- 此处渲染count来自vue组件,computed选项,随值改变而改变渲染 -->
		<h3>{{count}}</h3>
		<!-- 此处渲染count2来自vue组件data选项,不随值改变而改变渲染 -->
		<h3>{{count2}}</h3>
		<!-- 直接调用vuex的state选项,不推荐,推荐是computed引用后再洹染 -->
		<h3>{{this.$store.state.count}}</h3>
		<input type='button' value="clickme +" v-on:click='incrementCount'>
		<hr/>
		<!-- 组件名称有大小写,模板调用用短线隔开
		如:studentV 转换成student-v -->
		<student-v></student-v>
	</div>
	<script>
		const store = new Vuex.Store({
		  state: {
		    count: 0,
		    student:'学生信息'
		  },
		  mutations: {
		    increment (state) {
		      state.count++
		    }
		  }
		})
		// 创建一个 student 组件
		const studentV = {
		  template: `<div>{{ student }}</div>`,
		  computed: {
		    student () {
		      return store.state.student+" "+store.state.count
		    }
		  }
		}
		
		var app=new Vue({
			el:'#app',
			data(){
				return{
					msg:'app.vue 组件',
					count2:this.$store.state.count
				}
			},
			store,
			components:{studentV},
		computed:{
			count:function(state) {
				return this.$store.state.count
			}
		},
		methods:{
			incrementCount:function(){
				//引用 vuex下的mutations选项书写的函数
				return this.$store.commit('increment')
			}
		}

		})
	</script>
</body>
</html>

 

posted @ 2019-08-15 10:26  码哥之旅  阅读(1567)  评论(0编辑  收藏  举报