Vue2双向绑定失效的情况

失效情况

情况1,对象新增的属性无法双向绑定

<template>
  <div class="hello">
    <el-row style="margin-top:10px;">
      <el-col :span="12">
        <el-input v-model="tempResponseObj.retCode" placeholder="请填写响应码"></el-input>
      </el-col>
    </el-row>

    <el-row style="margin-top:10px;">
      <el-col :span="12">
        <el-input v-model="tempResponseObj.retMsg" placeholder="请填写响应值"></el-input>
      </el-col>
    </el-row>

    <el-row style="margin-top:10px;">
      <el-col :span="12">
        <el-button type="primary" @click="setRetMsg">点击</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      tempResponseObj: {
        retCode: "200"
      }
    }
  },
  watch: {},
  created() {},
  methods: {
    setRetMsg() {
      console.log("setRetMsg method start");
      this.tempResponseObj["retMsg"] = "操作成功!";
      console.log("setRetMsg method end");
    },
  }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>

image

情况2,数组内部对象增加的属性无法双向绑定

<template>
    <div class="hello">
        <el-row :style="{'margin-top':'10px'}">
            <el-col :span="12">
                <el-input v-model="tempResponseArray[0].name" placeholder="姓名"></el-input>
                <el-input v-model="tempResponseArray[0].age" placeholder="年龄"></el-input>
                <el-input v-model="tempResponseArray[0].phone" placeholder="电话"></el-input>
            </el-col>
        </el-row>
    
        <el-row style="margin-top:10px;">
            <el-col :span="12">
            <el-button type="primary" @click="addArrayItem">点击</el-button>
            </el-col>
        </el-row>

    </div>
  </template>
  
  <script>
  export default {
    name: 'HelloWorld',
    data () {
      return {
        tempResponseArray: [
            {
                name: '张三',
                age: '30'
            }
        ]
      }
    },
    watch: {},
    created() {},
    methods: {
      addArrayItem() {
        console.log("addArrayItem method start");
        this.tempResponseArray[0]["phone"] = "123456789";
        console.log("addArrayItem method end");
      }
    }
  }
  </script>
  <!-- Add "scoped" attribute to limit CSS to this component only -->
  <style scoped></style>

image

解决方法

this.$set(对象, 属性名, 属性值);

// 情况1例子
this.$set(this.tempResponseObj, "retMsg", "操作成功");
// 情况2例子
this.$set(this.tempResponseArray[0], "phone", "123456789");
posted @ 2025-05-25 11:47  sunpeiyu  阅读(44)  评论(0)    收藏  举报