道具参数在安装程序中不是被动的

人气:371 发布:2022-10-16 标签: vue.js vuejs3 vue-props

问题描述

我正在尝试开发一个组件来编译给定的html;我成功地使用了常量html文本,但无法使用更改的html文本。

main.js

app.component("dyno-html", {
  props: ["htmlTxt"],
  setup(props) {
    watchEffect(() => {
      console.log(`htmlText is: ` + props.htmlTxt);
      return compile(props.htmlTxt);
    });
    return compile(props.htmlTxt);
  },
});

Home.js

<template>
  <div class="home">
    <dyno-html
      :htmlTxt="html2"
      :bound="myBoundVar"
      @buttonclick="onClick"
    ></dyno-html>
    -------------
    <dyno-html
      :htmlTxt="html"
      :bound="myBoundVar"
      @buttonclick="onClick"
    ></dyno-html>
  </div>
</template>

<script>
export default {
  name: "Home",
  components: {},
  data: function() {
    return {
      html: "",
      html2: `<div> Static! <button @click="$emit('buttonclick', $event)">CLICK ME</button></div>`
    };
  },
  mounted() {
    // get the html from somewhere...
    setTimeout(() => {
      this.html = `
        <div>
          Dynamic!
          <button @click="$emit('buttonclick', $event)">CLICK ME</button>
        </div>
      `;
    }, 1000);
  },
  methods: {
    onClick(ev) {
      console.log(ev);
      console.log("You clicked me!");
      this.html2 = "<b>Bye Bye!</b>";
    },
  },
};
</script>

结果:

控制台:

htmlText的更改似乎到达了设置函数,但不影响编译函数!

推荐答案

这是预期行为,因为正确的值被读取一次并导致静态呈现函数。

应在Render函数内部读取正确的值。可以用计算来包装它,以避免不需要的编译器调用:

const textCompRef = computed(() => ({ render: compile(props.htmlTxt) }));
return () => h(textCompRef.value);

772