简体   繁体   English

Vue 组件直到模板中的值才具有反应性

[英]Vue component not reactive until value in template

I have a child component in Vue.我在 Vue 中有一个子组件。 I also use Vuex for some values.我也将 Vuex 用于某些值。

When I click something in the parent component, the child component should be triggered.当我单击父组件中的某些内容时,应触发子组件。 I do that by sending an active (bool) as prop to the child component.我通过向子组件发送一个active (bool)作为道具来做到这一点。

In the updated method I do what needs to be done when the component is triggered.updated方法中,我执行触发组件时需要执行的操作。

Problem问题

In order for updated to be triggerd, I need to add active to my template.为了触发updated ,我需要将active添加到我的模板中。 Else it's not triggered.否则不会触发。 So my really hackish solution right now is to use v-show="!active || active" which says, "always show the div".所以我现在真正的hackish解决方案是使用v-show="!active || active" ,它说,“总是显示 div”。

How can I trigger the component without a hack like this?如何在没有像这样的黑客攻击的情况下触发组件? I don't need the active value in my template.我的模板中不需要active值。

Complete child component完整的子组件

Vue.component('p-inline-readonly', {
  mixins: [ table_mixin ],
  props: {
    value: [ String, Number ],
    active: Boolean
  },
  updated() {
    this.reset();
    this.refocus();
  },
  template: /*html*/ `
    <div class="slot p-inline-readonly">
      <div class="presentation" v-show="!active || active">
        {{value}}
      </div>
    </div>
  `
});

You could watch active and trigger an update:您可以观看active并触发更新:

watch: {
    active: function(val, oldVal) {
      this.$forceUpdate();
    },
}

You may also add a key to the child component:您还可以向子组件添加一个键:

<p-inline-readonly :key="active" ... >

This will make the component rerender when active change, but won't call the updated hook so you would need to move its logic to a different hook like mounted这将使组件在活动更改时重新呈现,但不会调用updated钩子,因此您需要将其逻辑移动到不同的钩子,如mounted

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM