vue基本用法

78 阅读1分钟

一、内容渲染元素

v-text:只占一位,会覆盖原有内容
{{ }} 只是内容占位符,不覆盖原有内容,只能显示在内容上,不能属性上
v-html:会覆盖原有内容

<template>
    <div id="myapp">
        <p>这是插值:{{ message }}</p>
        <p v-text="message">这是v-text:</p>
        <p v-html="info">这是v-text:</p>
    </div>
</template>
<script>
export default {
    data() {
        return {
            message: 0,
            info: '<h1 style="background-color:red">这是v-html</h1>'
        }
    }
}
</script>

image.png

二、属性绑定

<template>
    <div id="myapp">
        <input type="text" :placeholder="message" />
    </div>
</template>
<script>
export default {
    data() {
        return {
            message: 'aaa',
        }
    }
}
</script>

三、插值加js

<template>
    <div id="myapp">
        <div>1+2的结果是: {{ 1 + 2 }}</div>
        <div>{{ tips }}反转的结果是{{ tips.split('').reverse().join('') }}</div>
        <div :title="'box' + index">这是一个div</div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            tips: 'aaabbbb',
            index: 1
        }
    }
}
</script>

在这之前都是在data里面定义的

四、事件绑定(在方法内定义)

<template>
    <div id="myapp">
        {{ index }}
        <button v-on:click="add">+</button>
        <button @click="sub(2)">-</button>
   //原生DOM对象有onclick,oninput,onkeyup等原生事件,替换vue事件绑定形式后,分别为v-on:click,v-on:input,v-on:keyup
        <button @click="mult(2, $event)">*</button>
        <button @click="chu">/</button>
    </div>
</template>
<script>
export default {
    data() {
        return {
            tips: 'aaabbbb',
            index: 1
        }
    },
    methods: {
        add: function () {
            this.index += 1
        },
        sub(n) {
            this.index -= n
        },
        mult(n, e) {
            this.index *= n
            e.target.style.backgroundColor = 'skyblue'
        },
        chu(e) {
            if (this.index % 2 == 0) {
                e.target.style.backgroundColor = 'red'
                this.index /= 2
            } else {
                e.target.style.backgroundColor = ''
            }
        }
    }
}
</script>

2.1事件修饰符

事件处理函数中调用event.preventDefault()或event.stopPropagation()
.prevent 阻止默认行为(a链接跳转,阻止表单提交)

 <a href="www.baidu.com" @click.prevent="show">跳转到百度首页

.stop阻止事件冒泡(不跳转)

<a href="www.baidu.com" @click.prevent="show">跳转到百度首页

.capture 捕获模式触发当前事件处理函数
.once 绑定事件只触发一次
.self 只有在event.target是当前元素自身触发事件处理函数\

2.2按键修饰符

<input type="text" @keyup.enter="enter" @keyup.esc="esc" />        
enter() {             
console.log('触发了enter属性')        
},        
esc() {            
console.log('触发了esc属性')        
}