关于挂载:
在main.js中:
import Vue from 'vue'
import App from './App.vue'
import './plugins/element.js'
Vue.config.productionTip = false
new Vue({
render: h => h(App)
}).$mount('#app')
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chorme=1">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>vue-project</title>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
注意这两句话:
<div id="app"></div>
new Vue({
render: h => h(App)
}).$mount('#app')
App.vue:
<template>
<div id="app">
{
{msg}}
</div>
</template>
<script>
export default {
name: 'app',
data () {
return {
msg: '我爱你'
}
}
}
</script>
<style>
#app {
color: blue;
}
</style>
结果:
绑定数据:
<template>
<div id="app">
{
{msg}}
<br>
<input type="text" v-model="msg"></input>
<button @click="num++">+</button>
<input type="text" size = "3" v-model="num">
<button @click="num--">-</button>
</div>
</template>
<script>
const data = {
msg: 'thisi is jinhnj',
num: 0
}
export default {
name: 'app',
data () {
return data
}
}
</script>
<style>
#app {
color: blue;
}
</style>
computed计算属性
<template>
<div id="app">
<h1>{
{getTitle()}}</h1>
<h1>{
{getTitle()}}</h1>
<h1>{
{getTitle()}}</h1>
<br>
<h2>{
{title}}</h2>
<h2>{
{title}}</h2>
<h2>{
{title}}</h2>
<small>{
{books[0].price+books[1].price}}</small>
<br>
总价:<small>$</small>{
{totalPrice}}
</div>
</template>
<script>
export default {
name: 'app',
data () {
return {
name: '学习',
slogen: '加油',
books: [
{
id: 1, name: '细说', price: 70 },
{
id: 1, name: '细说Ph第三版', price: 138 },
{
id: 1, name: '细说Ph第三版', price: 54 },
{
id: 1, name: '细说Ph第三版', price: 28 }
]
}
},
computed: {
totalPrice: {
get () {
return this.books.reduce((s, n) => s + n.price, 0)
}
},
title: {
set (values) {
let arr = values.split('-')
this.name = arr[0]
this.slogen = arr[1]
},
get () {
console.log('11111111')
return this.name + this.slogen
}
}
},
methods: {
getTitle () {
console.log('222222222')
this.title = '学习猿地- slogen'
return this.title
}
}
}
</script>
<style>
#app {
color: blue;
}
</style>
注意: < h1>{
{getTitle()}}< /h1>这句话要加上括号,否则无法显示内容
computed 属性默认只有 getter ,不过在需要时你也可以提供一个 setter ,set方法用得比较少,了解即可
return this.books.reduce((s, n) => s + n.price, 0)
表示每一步都将s + n.price的值赋给s,s的初始为0
我们可以使用 methods 来替代 computed,效果上两个都是一样的,但是 computed 是基于它的依赖缓存,只有相关依赖发生改变时才会重新取值。而使用 methods ,在重新渲染的时候,函数总会重新调用执行。
可以看到效果图:
其中1111只打印了一遍,而2222打印了三遍
事件监听v-on
用绑定事件或者语法糖事件的对比:
注意 v-on:click=“sub()”
@click = “sub”