文章目录
- 01-邂逅Vue3和Vue3开发体验
- Vue3带来的变化
- 如何使用Vue
- 方式一:CDN引入
- 方式二——下载和引入
- 计数器案例
- 原生实现
- Vue实现
- MVVM
- template
- 写法一
- 写法二
- data
- method
- 其他属性
01-邂逅Vue3和Vue3开发体验
Vue3带来的变化
如何使用Vue
方式一:CDN引入
<div id="app"></div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const why = {
template: `<h2>hello world</h2>`
}
const app = Vue.createApp(why)
app.mount("#app")
</script>
方式二——下载和引入
<div id="app"></div>
<script src="../js/vue.js"></script>
<script>
Vue.createApp({
template: `<h2>你好 世界</h2>`
}).mount("#app")
</script>
计数器案例
原生实现
<h2 class="counter">0</h2>
<button class="increment">+1</button>
<button class="decrement">-1</button>
<script>
// 获取所有元素
const counterEl = document.querySelector(".counter")
const incrementEl = document.querySelector(".increment")
const decrementEl = document.querySelector(".decrement")
// 定义变量
let counter = 100
counterEl.innerHTML = counter
// 监听按钮的点击
incrementEl.addEventListener('click', () => {
counter += 1
counterEl.innerHTML = counter
})
decrementEl.addEventListener('click', () => {
counter -= 1
counterEl.innerHTML = counter
})
</script>
Vue实现
<div id="app"></div>
<script src="../js/vue.js"></script>
<script>
Vue.createApp({
template: `
<h2>{{message}}</h2>
<h2>{{counter}}</h2>
<button @click="increment">+1</button>
<button @click="decrement">-1</button>
`,
data: function () {
return {
message: "hello world",
counter: 100
}
},
methods: {
increment() {
this.counter++
},
decrement() {
this.counter--
}
},
}).mount("#app")
</script>
MVVM
template
写法一
<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() {
this.counter++
},
decrement() {
this.counter--
}
},
}).mount("#app")
</script>
</body>
写法二
<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>
</div>
</template>
<script src="../js/vue.js"></script>
<script>
Vue.createApp({
template: '#why',
data: function () {
return {
message: "hello world",
counter: 100
}
},
methods: {
increment() {
this.counter++
},
decrement() {
this.counter--
}
},
}).mount("#app")
</script>
</body>