×

vue开发:学习this.$set动态绑定数据的应用

作者:jiang2021.02.23来源:Web前端之家浏览:5438评论:0
关键词:jsvuejs

vue开发:学习this.$set动态绑定数据的应用。话不多说直接上代码:

<template>
  <div>
    <!-- 单个数据 -->
    <button @click="text0a">text0</button>
    <p>text0: {{text0}}</p>
    <!-- 对象 -->
    <button @click="textObja">textObj</button>
    <p>textObj.text1: {{textObj.text1}}</p>
    <!-- 数组 -->
    <button @click="textArra">textArr</button>
    <p>textArr[1]: {{textArr[1]}}</p>
    <!-- json数据 -->
    <button @click="textJsona">textJson</button>
    <p>textJson[1].t5: {{textJson[1].t5}}</p>
  </div>
</template>
<script>
export default {
  data() {
    return{
      text0 : '',
      textObj: {},
      textArr: [],
      textJson:[
        {t0: ''},
        {t4: ''},
        {t7: ''},
      ]
    }
  },
  methods: {
    text0a: function () {
      let vm = this
      let text100 = 'efghjk'
      vm.$set(vm,'text0',text100) 
      //等效于 vm.$set(vm,'text0','efghjk')
    },
    textObja: function () {
      let vm = this
      let textObj100 = {
        text1: '123',
        text2: '456'
        }
      vm.$set(vm.textObj,'text1',textObj100.text1) 
      //此时等效于 vm.$set(vm,'textObj',textObj100)
    },
    textArra: function () {
      let vm = this
      let textArr200 = ['a1','a2','a3']
      vm.$set(vm,'textArr',textArr200)
    },
    textJsona: function () {
      let vm = this
      let textJson300 = [
        {t1: 't1',t2: 't2',t3: 't3'},
        {t4: 't4',t5: 't5',t6: 't6'},
        {t7: 't7',t8: 't8',t9: 't9'},
      ]
      vm.$set(vm.textJson[1],'t5',textJson300[1].t5) 
      //此时等效于 vm.$set(vm,'textJson',textJson300)
    }
  }
}
</script>
<style>
</style>

补充:Vue 使用$set动态给数据设置属性

在实际的开发过程中,给表单元素绑定model的时候,绑定的元素的属性是根据后台数据动态生成的。如果使用常规的赋值方式,是无法更新视图的

需要使用

this.$set(dataName,keyName,keyValue)
export default {
 data:{
  // 先定义一个空对象
  formObject:{},
  arrayList:[],
 },
 mounted() {
  this.initPage()
 },
 methods:{
  initPage(){
   this.$store.dispatch(namespace/callData).then(res=>{
    // 给数据设置key-value
    res.data.forEach(item=>{
     //  this.formObject[item.name] = item.value //  这种方式是不能更新视图的
     this.$set(this.formObject, item.name, item.value) // 可以更新视图
    })
   })
   // 修改数组
    this.$store.dispatch(namespace/callData).then(res=>{
    // 给数据设置key-value
    this.$set(this.arrayList,0,(res.data)[0].id) 可以更新视图
   })
  }
 }
}

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/js20200223a1.html

网友评论文明上网理性发言 已有0人参与

发表评论: