65. VUE Mutation响应规则

现在我的state中的变量user 有一个人:  

我需要添加一个属性给他,即:【这里不用JS函数】

 

运行发现 页面并没有添加这个address,但是肖丽雅的属性中是包含address的,说明这没有做到响应式:

所以这种方式是做不到响应式的,除了JS函数 还可以这样: VUE.set(xx,yy,zz):

  这个函数三个属性 圈起来了  这样写即可:

因为我们user是对象 所以第二个属性用 key:

具体代码如下:

<template>
  <div id="app">
       <table>
      <thead>
        <tr>
          <th>姓名</th>
          <th>年龄</th>
          <th>爱好</th>
          <th>生日</th>
          <th>地址</th>
        </tr>
      </thead>
      <tbody>
          <tr v-for="(item,index) in $store.state.user" :key="index">
            <td>{{item.name}}</td>
            <td>{{item.age}}</td>
            <td>{{item.hobby}}</td>
            <td>{{item.birthday}}</td>
            <td>{{item.address}}</td>
          </tr>

      </tbody>
    </table>

      <br><br>
      <button @click="addAttribute">添加新属性address</button>
  </div>
</template>
  

<script>
export default {
  methods:{
        addAttribute(){
          const add = "北京朝阳";
          this.$store.commit('addAttribute',add);
        }
    }
    
  }
  
</script>


<style scoped>
  table{
    border: 1px black solid;
    border-collapse: collapse;
    border-spacing: 0;
}

th,td{
padding: 8px 16px;
border: 1px solid black;
    text-align: left;
}

th{
    background-color: #f7f7f7;
    color: black;
    font-weight: 600;
}
</style>
App.vue App组件
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)   


const myVuex = new Vuex.Store({
    state:{
        user:
        [
            {name:"肖丽雅",age:18,hobby:'Basketball',birthday:'2002-5-16'},
        ],

    },             

    mutations:{                     
        addAttribute(state,payload){
            Vue.set(state.user[0],"address",payload)
        }
    },              
    
    getters:{
        
    },
    actions:{},
    modules:{},
});


export default myVuex   //导出VUX对象
index.js VUEX配置文件

说了添加响应式 来一个删除的:

delete  这个可以直接删除属性的,但是也做不到响应式:

    

可以发现 虽然是没了 单身视图不会响应式:

那么除了JS函数 我们还可以用 vue.delete 来完成:

  两个参数 ,,因为我们这里是对象 所以第二个参数用 key即可:

这样就可以响应式了:

 可以看到 名字没了。

本文来自博客园,作者:咸瑜,转载请注明原文链接:https://www.cnblogs.com/bi-hu/p/15168956.html

原文地址:https://www.cnblogs.com/bi-hu/p/15168956.html