在传统原生HTML应用中,也可像vue2一样使用VUE3的这一特性示例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<script src="https://unpkg.com/vue@3.3.4/dist/vue.global.js"></script>
<title>单页面使用Vue</title>
</head>
<body>
<h1>HTML页面嵌入部分使用Vue3,在jQuery应用中用类似Vue2使用Vue3</title></h1>
<div id="app">
{{ state }}
<button v-on:click="addOne">Add One</button>
<button v-on:click="minOne">Min One</button>
<h1 v-if="state % 2 === 0">Vue is even!</h1>
</div>
</body>
<script>
const { createApp, reactive, toRefs } = Vue;
const data = reactive({
state: 12,
minOne() {
data.state--;
},
})
const app = createApp({
setup() {
return {
...toRefs(data),
addOne() {
data.state++
}
}
}
});
app.mount("#app");
</script>
</html>
更加复杂一点的例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<script src="https://unpkg.com/vue@3.3.4/dist/vue.global.js"></script>
<title>单页面使用Vue</title>
</head>
<body>
<h1>HTML页面嵌入部分使用Vue3</title></h1>
<div id="app">
<ul>
<li v-for="(user, index) in users">
<input v-model="user.name">
<button v-on:click="removeUser(index)">Remove User</button>
</li>
</ul>
<button v-on:click="addUser">Add User</button>
<p v-for="(user, index) in users">{{user.name}}</p>
</div>
</body>
<script>
const { createApp, reactive, toRefs } = Vue;
const data = reactive({
users: [
{ name: 'Foo' },
{ name: 'Bar' },
{ name: 'Two' },
],
addUser() {
data.users.push({ name: '' })
},
removeUser(index) {
data.users.splice(index, 1)
},
})
const app = createApp({
setup() {
return {
...toRefs(data)
}
}
});
app.mount("#app");
</script>
</html>
也可将事件分离出来:
<script>
const { createApp, reactive, toRefs } = Vue;
const data = reactive({
users: [
{ name: 'Foo' },
{ name: 'Bar' },
{ name: 'Two' },
],
})
const handlers = {
addUser() {
data.users.push({ name: '' })
},
removeUser(index) {
data.users.splice(index, 1)
},
}
const app = createApp({
setup() {
return {
...toRefs(data),
...handlers,
}
}
});
app.mount("#app");
</script>
可见vue3比vue2更灵活