如何查看 Vue.js 组件中的道具变化? [英] How to watch prop change in Vue.js component?

查看:22
本文介绍了如何查看 Vue.js 组件中的道具变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一组图像文件路径传递给组件.我想知道如果我传递不同的数组,在 Vue.js 组件中观察道具变化的最佳方式是什么?

我正在使用引导轮播,所以想在数组更改时将其重置为第一个图像.为了简单起见,我将代码示例简化为:

Vue.component('my-images', {道具:['图像'],模板:`<部分><div v-for="(image, index) in images">{{index}} - <img :src="image"/></div></部分>`});

解决方案

<template>

{{count}}</div></模板><脚本>导出默认{名称:'测试',道具:['count'],手表: {'$道具':{处理程序:函数(val,oldVal){console.log('watch', val)},深:真}},挂载(){控制台.log(this.count)}}</脚本>

I'm passing an array of image filepaths to a component. I'm wondering what would be the best way to watch a prop change in Vue.js component, if I pass a different array?

I'm using bootstrap carousel, so wanna reset it to first image when array changes. In order for simplicity I reduced code example to this:

Vue.component('my-images', {
  props: ['images'],

  template: `
    <section>
      <div v-for="(image, index) in images">
        {{index}} - <img :src="image"/>
      </div>
    </section>
  `
});

解决方案

<template>
  <div>
    {{count}}</div>
</template>

<script>
export default {
  name: 'test',
  props: ['count'],
  watch: {
    '$props':{
      handler: function (val, oldVal) { 
        console.log('watch', val)
      },
      deep: true
    }
  },
  mounted() {
    console.log(this.count)
  }
}
</script>

这篇关于如何查看 Vue.js 组件中的道具变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆