【VUE】快速上手
一、快速上手
- 创建HTML文件+引入vue.js
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/3.3.4/vue.global.prod.js"></script>
- 按照vue.js的语法编写代码
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><script src="https://cdn.bootcdn.net/ajax/libs/vue/3.3.4/vue.global.prod.js"></script>
</head>
<body>
<div id="app"><h1>欢迎光临红浪漫,尊贵的VIP:{{ name }}, 余额{{ balance }}</h1><button @click="doCharge">点击充值</button><button @dbclick="doCharge2">双击充值</button>
</div><script>var app = Vue.createApp({data: function () {return {name: "cqn",balance: 199}},methods:{doCharge: function () {this.name = 'zkf'this.balance = 299},doCharge2: function () {this.balance = this.balance + 1000}}});app.mount("#app")
</script>
</body>
</html>
vue语法操作和传统方式页面的操作的区别:
- 传统方式页面功能:DOM中寻找标签+操作
- vue.js的页面功能:js变量 <-> DOM中标签进行双向绑定,修改js中的变量,页面内容会实时发生变化
<div id="city"><h1>中国北京</h1>
</div><script>v1 = document.getElementById("city")v1.innerText="广东深圳"
</script>
二、组合式和选项式
Vue3支持的两种开发模式API:组合式和选项式
- 选项式:简单,容易上手,需要使用this获取data-return中返回的值
Vue.createApp({data:...methods:...})
- 组合式:修改变量时同步至页面,变量设置时,需要加Vue.ref(“”),变量读取时,需要加.value,修改时,也要加.value
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><script src="https://cdn.bootcdn.net/ajax/libs/vue/3.3.4/vue.global.prod.js"></script>
</head>
<body>
<div id="bob"><h1>欢迎光临红浪漫,尊贵的VIP:{{ name }}, 余额{{ balance }}</h1><button @click="doCharge">点击充值</button><button @dbclick="doCharge2">双击充值</button>
</div><script>var bob = Vue.createApp({setup: function () {var name = "cqn"var balance = Vue.ref(1000)var doCharge = function () {balance.value = 9999console.log(name, balance.value)}var doCharge2 = function () {console.log(name, balance.value)}return {name, balance, doCharge, doCharge2}}});bob.mount("#bob")
</script>
</body>
</html>
- 解包
var Vue = {name: "cqn", age: 19, email: "xxx"}var {name, age} = Vueconsole.log(name, age)const {createApp, ref} = Vue
- 导包
import {createApp, ref} from 'ttt.js'
- 常量和变量
- 变量:var name = “cqn” // 可以被修改 name = ‘zkf’
- 常量:const age = 19 // 不可以被修改 age = 18 -> 不支持
- 常量:const info = { v1:19, v2:30 } // info = {} ->不支持,但是info.v1=18支持