template 模板属性
说明
写法
写法1、x-template
这个时候,在createApp的对象中,我们需要传入的template以 # 开头,
如果字符串是以 # 开始,那么它将被用作 querySelector,并且使用匹配元素的 innerHTML 作为模板字符串
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">哈哈哈哈啊</div>
<script type="x-template" id="why">
<div>
<h2>{{message}}</h2>
<h2>{{counter}}</h2>
<button @click='increment'>+1</button>
<button @click='decrement'>-1</button>
</div>
</script>
<script src="../js/vue.js"></script>
<script>
Vue.createApp({
template: '#why',
data: function() {
return {
message: "Hello World",
counter: 100
}
},
// 定义各种各样的方法
methods: {
increment() {
console.log("点击了+1");
this.counter++;
},
decrement() {
console.log("点击了-1");
this.counter--;
}
}
}).mount('#app');
</script>
</body>
</html>
写法2、任意标签设置id
通常使用template标签,因为不会被浏览器渲染。
template元素是一种用于保存客户端内容的机制,该内容再加载页面时不会被呈现,但随后可以在运行时使用JavaScript实例化;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<template id="why">
<div>
<h2>{{message}}</h2>
<h2>{{counter}}</h2>
<button @click='increment'>+1</button>
<button @click='decrement'>-1</button>
<button @click="btnClick">按钮</button>
</div>
</template>
<script src="../js/vue.js"></script>
<script>
document.querySelector("#why")
Vue.createApp({
template: '#why',
data: function() {
return {
message: "Hello World",
counter: 100
}
},
// 定义各种各样的方法
methods: {
increment() {
console.log("点击了+1");
this.counter++;
},
decrement() {
console.log("点击了-1");
this.counter--;
},
btnClick: () => {
// this === window? 不可以
// 写成一个箭头函数时, 这个this就是window
// 在箭头函数中是不绑定this, 但是函数中如果使用了this
console.log(this);
},
btn2Click: function() {
// this === window? 不可以
// 写成一个箭头函数时, 这个this就是window
// 在箭头函数中是不绑定this, 但是函数中如果使用了this
console.log(this);
}
}
}).mount('#app');
</script>
</body>
</html>
==========================
data 数据属性
==========================
methods 方法属性
=========================
其他属性
props、computed、watch、emits、setup 等
=========================
setup Vue3函数编程属性
参考 https://www.yuque.com/yejielin/mypn47/uk9tee#LrQ3k
可以把data、methods等属性都一并使用,有助于分开逻辑和变量