【问题标题】:vuejs reactivity without template没有模板的 vuejs 反应性
【发布时间】:2017-09-30 19:14:39
【问题描述】:

我有一个带有空模板的 Vue 组件,需要监听 prop 更改:

// component.vue
<template>
</template>

<script>
  export default {
    props: ['mode'],
    updated: function() {
      console.log('updated!')
    }
  }
</script>

//parent.vue
<template>
  ...
  <childcomponent :mode="variable"></childcomponent>
</template>
...

现在,每当父级的 variable 更改时,我希望 childcomponent.updated 会被调用。但是,这似乎只有在子模板中使用该道具时才会发生。

到目前为止我想出的唯一解决方法是将子组件的模板设置为&lt;div v-show="false&gt;{{ mode }}&lt;/div&gt;,但这看起来真的不对吗?有没有更好的方法来解决我的问题?

我首先使用空模板的原因是该组件与 js 库进行交互,该库本身执行大量 DOM 操作。

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    如果你不需要创建任何 DOM 元素,你可以watch props 并使用空的render 函数:

    new Vue({
      el: '#app',
      data: {
        word: ''
      },
      components: {
        'child' : {
          props: ['myprop'],
          watch: {
          	myprop: function(n, o) {
              console.log('changed to: ', n)
            }
          },
          render: function(h) {
          	return h() // avoid warning message
          }
        }
      }
    });
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    
    <div id="app">
      <child :myprop="word"></child>
      <button @click="word = 'one'">One</button>
      <button @click="word = 'two'">Two</button>
      <button @click="word = 'three'">Three</button>
    </div>

    【讨论】:

    • 好吧,我想我应该继续阅读有关计算属性的文档。非常感谢!:)
    猜你喜欢
    • 2018-11-12
    • 2020-07-25
    • 2020-01-31
    • 2019-12-24
    • 1970-01-01
    • 2017-05-03
    • 2018-09-11
    • 2018-07-20
    • 2019-06-22
    相关资源
    最近更新 更多