最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - vuejs reactivity without template - Stack Overflow

programmeradmin16浏览0评论

I have a Vue ponent with an empty template that needs to listen to prop changes:

// ponent.vue
<template>
</template>

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

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

Now whenever the parent's variable changes, I would expect childponent.updated to be called. However, this only seems to happen if the prop is used in the child's template.

The only workaround I came up with so far is to set the child ponent's template to <div v-show="false>{{ mode }}</div>, but that really doesn't seem right? Is there a nicer way to solve my issue?

The reason I'm using an empty template in the first place is because the ponent interacts with js library that does a bunch of DOM manipulations itself.

I have a Vue ponent with an empty template that needs to listen to prop changes:

// ponent.vue
<template>
</template>

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

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

Now whenever the parent's variable changes, I would expect childponent.updated to be called. However, this only seems to happen if the prop is used in the child's template.

The only workaround I came up with so far is to set the child ponent's template to <div v-show="false>{{ mode }}</div>, but that really doesn't seem right? Is there a nicer way to solve my issue?

The reason I'm using an empty template in the first place is because the ponent interacts with js library that does a bunch of DOM manipulations itself.

Share Improve this question asked May 3, 2017 at 5:39 GeotobGeotob 2,9451 gold badge19 silver badges26 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

You can watch props and use empty render function if you don't need to create any DOM elements:

new Vue({
  el: '#app',
  data: {
    word: ''
  },
  ponents: {
    '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./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>

发布评论

评论列表(0)

  1. 暂无评论