vue 如何拿到this.data后的回调函数

<script>
  export default {
    data () {
      return {
        radio: '1'
      };
    },
    methods: {
      change(){
        this.radio = '2' //这里该怎么拿到this.radio的回调函数
      }
    }
  }
</script>

用watch监听可以达到效果,不过有没有像react这样,同样是set data数据,react的回调函数是这样写的 ↓

this.setState({data:123},() => {
     console.log(this.state.data) //123 
  })

那么vue的该怎么写呢~~

问题详情如上,在这里先感谢各位大哥们的解答,小弟感激不尽!

阅读 4.5k
5 个回答

vue更改data上的数据是同步的,因为你直接改的就是this.data = ...;而不是像react那样调用一个函数,如果你是想更新后的数据渲染到视图再触发回调则使用nextTick API

可以用watch来监听

methods: {
      change(){
        this.radio = '2' //这里该怎么拿到this.radio的回调函数
      }
},
watch: {
    radio(newValue, oldValue){
        console.log(newValue)
    }
}

它是同步的

change(){
        this.radio = '2' //这里该怎么拿到this.radio的回调函数
        console.log(this.radio) //'2'
      }

可以看一下computed的set

不知道是不是这种效果,没用过react

data() {
    return {
      radioData: 1
    }
  }, 
  computed: {
    radio: {
        get: function () {
          return this.radioData
        },
        set: function (val) {
          this.radioData = val
          console.log(this.radio) // 3
        }
    }
  },
  methods: {
    change () {
      console.log(this.radio) // 1
      this.radio = 3
    }
  }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题