道具参数在安装程序中不是被动的 [英] Props arguments are not reactive in setup

查看:2
本文介绍了道具参数在安装程序中不是被动的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开发一个组件来编译给定的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);

这篇关于道具参数在安装程序中不是被动的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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