即使从应用程序外部输入数据,也不会反映出来

Even if data is entered from outside the app, it will not be reflected

如果您尝试从应用程序外部分配一个变量,它不会很好地反映出来。 为什么行为会根据应用程序在 HTML 标记上的安装方式而改变?

此代码无效

<div id="app">
  <ul v-for="player in players">
    <li>{{player.name}}, {{player.age}}</li>
  </ul>
</div>

<!-- VueJS -->
<script src="https://unpkg.com/vue@3.2.20"></script>

<script>
let app= Vue.createApp({
    data() {
        return {
            players : []
        }
    },
})

app.mount("#app") //<--- here

app.players=[
    {name: 'nobita', age: 13},
    {name: 'suneo', age: 13},
    {name: 'sizuka', age: 13},
    {name: 'takeshi', age: 13},
]

</script>

此代码有效:

<div id="app">
  <ul v-for="player in players">
    <li>{{player.name}}, {{player.age}}</li>
  </ul>
</div>


<script>
let app= Vue.createApp({
    ...
}).mount("#app")  //<--- here


app.players=[
    {name: 'nobita', age: 13},
    {name: 'suneo', age: 13},
    {name: 'sizuka', age: 13},
    {name: 'takeshi', age: 13},
]

</script>

Vue.createApp() 创建一个 application instance, used to configure the application setup, such as registering components, directives, and global props. The application instance returns the root component in its mount() API.

如您所见,组件数据只能通过组件引用进行更新。