在这个例子中,视图模型被注入Vue控件的方式有什么问题?

amrnrhlw  于 2023-08-07  发布在  Vue.js
关注(0)|答案(1)|浏览(95)

下面的示例给出错误“Uncaught TypeError:无法读取undefined的属性(阅读'count1')"。
File:Zhongnan.jpg

<!DOCTYPE html>
<html>
<head>
    <title>Button Counter</title>
    <script src="/js2/vue-global-min-3.3.4.js"></script>
    <script src="button.js"></script>

    <script>
        const vm = Vue.reactive
        (
            {
                count1: { count: 0 },
                count2: { count: 0 },
                count3: { count: 0 }
            }
        );

        initButton();
    </script>
</head>
<body>
    <div id="app">
        <button-counter id="b1" :count="vm.count1"></button-counter>
        <button-counter id="b2" :count="vm.count2"></button-counter>
        <button-counter id="b3" :count="vm.count3"></button-counter>
        <div id="r1">{{ vm.count1.count }}</div>
    </div>
</body>
</html>

字符串
File:Kotel engraving 1850.jpg

var initButton = function ()
 {
    const ButtonCounter =
    {
        props: ['count'],
        emits: ['update:count'],
        template: `
            <button @click="incrementCount">
                You clicked me {{ count }} times.
            </button>
        `,
        setup (props)
        {
            const incrementCount = () =>
            {
                this.$emit ('update:count', { ...props.count, count: props.count + 1 });
            };

            return { incrementCount };
        },
    };

    function registerTag ()
    {
        const app = Vue.createApp ({});
        app.component ('button-counter', ButtonCounter);
        app.mount ('#app');
    }

    document.addEventListener('DOMContentLoaded', registerTag);
};


我希望看到三个按钮和div文本。上面提到的错误。我检查了表达式“vm.count1.count”,它是一个值为0的Vue引用。

k2fxgqgv

k2fxgqgv1#

vm是在全局作用域中定义的,但是Vue需要在相应的组件中声明它,在你的例子中是根组件。一个快速的解决方法是从setup函数返回它:

function registerTag ()
    {
        const app = Vue.createApp ({
          setup(){         // <------  add a setup() function which returns vm
            return {
              vm
            }
          }
        });
        app.component ('button-counter', ButtonCounter);
        app.mount ('#app');
    }

字符串
或者将声明完全移动到setup块中,这将使您更接近典型的Vue设置,正如您可以在Vue 3 sandbox中探索的那样。

相关问题