外观
在网页中嵌入Vue
Vue能够直接嵌入到网页中,像使用JQuery一样,但是比JQuery操作DOM的能力更强。
下面通过两种API风格演示如何在网页中嵌入Vue。有关API风格,请向下翻阅,这里只需要懂基本原理即可。
示例:
<!-- 选项式API -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
</style>
</head>
<body>
<div id="app"> <!-- 为Vue控制的区域创建一个选择器 -->
<span>{{ count }}</span>
<button @click="increment">添加</button>
</div>
<script type="module"> // 在这里导入Vue,添加type="module",这样浏览器就会将js文件当做模块来处理
import {createApp} from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'; // 导入Vue
createApp({ // 创建一个Vue实例
data() { // 在这里定义数据
return {
count: 0 // 初始化数据
}
},
methods: { // 方法定义
increment: function () {
this.count++;
}
},
mounted: function () { // 元素被挂载到页面上后执行
console.log('Vue组件已被创建。');
}
}).mount('#app'); // 在这里用mount方法渲染,将Vue组件挂载到id为app的元素上
</script>
</body>
</html><!-- 组合式API -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
</style>
</head>
<body>
<div id="app"> <!-- 为Vue控制的区域创建一个选择器 -->
<span>{{ count }}</span>
<button @click="increment">添加</button>
</div>
<script type="module"> // 在这里导入Vue,添加type="module",这样浏览器就会将js文件当做模块来处理
import {createApp, ref, onMounted} from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';
createApp({ // 创建一个Vue实例
setup() {
const count = ref(0); // 创建一个响应式变量
function increment() {
count.value++;
}
onMounted(() => { // 相当于选项式API的mounted函数
console.log('Vue组件已经被挂载')
})
return {
count, increment //在这里返回要在页面中出现的方法和变量
}
}
}).mount('#app'); // 在这里用mount方法渲染,将Vue组件挂载到id为app的元素上
</script>
</body>
</html>