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

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

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

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<!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 @   码哥之旅  阅读(1569)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示