Vue解除数据双向绑定

文章描述:

  let obj = JSON.parse(JSON.stringify(data)); 将对象转 […]

 

let obj = JSON.parse(JSON.stringify(data));

将对象转为json字符串之后再转对象就能解除掉数据的双向绑定

vue页面
<template>
  <div id="app">
    <div class="container">
      <div v-for="(item,index) in list" :key="index" class="item">
          <div class="label" v-if="!item.has">
            {{item.id}} {{item.name}}
          </div>
          <div v-if="!item.has" @click="clickHandle(index)">
              编辑

          </div>
          <inputItem v-if="item.has" :item="item" @closeClick="close"></inputItem>
      </div>
    </div>
  </div>
</template>

<script>
import inputItem from "@/views/debug/components/inputItem";
export default {
  name: 'App',
  components:{
    inputItem
  },
  data(){
    return {
      list:[
        {id:1,name:'123',has:false},
        {id:2,name:'456',has:false},
        {id:3,name:'789',has:false},
        {id:4,name:'111',has:false},
      ],
      item:""
    }
  },
  mounted(){

  },
  methods:{
    close(val){
      console.log('取消恢复值:',val)
      this.list.forEach((item,i)=>{
        if(this.list[i].id==val.id){
          this.list[i] = val
          this.list[i].has = false
        }
      })
      // 强制渲染
      this.$forceUpdate()
    },
    clickHandle(index){
      this.list.forEach((item,i)=>{
        if(item.id == this.list[index].id){
          item.has = true
        }else{
          item.has = false
        }
      })
      // this.list[index].has = true
      this.item = this.list[index]
    }
  }
}
</script>

<style lang="scss">
.container{
  padding: 20px 20px;
}
.item{
  display: flex;
  justify-content: flex-start;
  padding: 10px 0;
  .label{
    width: 120px;
  }
}
</style>

 

组件

<template>
  <div>
    <input type="text" v-model="item.name" />
    <div>

      <el-button type="warning"  size="mini" @click="cancelClick">取消</el-button><el-button type="primary"  size="mini" >保存</el-button>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    item: {
      type: Object,
      default: "",
    },

  },
  data(){
    return{
      oldValue: JSON.parse(JSON.stringify(this.item)),
      newValue: ''
    }
  },
  watch: {
    newValue: function(val, oldVal) {
      // 将旧值保存下来
      this.oldValue = oldVal;
    }
  },
  created() {
    console.log('传给组件的值:',this.item)
  },
  methods: {
    // 取消
    cancelClick:function(){
      // 将数据恢复到之前的状态
      this.newValue = this.oldValue;

      let obj = this.newValue
      this.$emit('closeClick',obj)
    },

  },
}
</script>

<style>
</style>

 

发布时间:2024/04/19

发表评论