← 返回首页
Vue3基础教程(二)
发表时间:2021-07-31 13:09:41
常用指令

与Vue2相比指令部分变化不大。常用的vue指令主要用于元素的文本、属性和事件的绑定,以及循环遍历等等。

1.文本/属性/事件的绑定

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/3.1.5/vue.global.prod.min.js"></script>
</head>
<body>
<div id="app">
    <!--文本绑定-->
    <h1 v-text="msg"></h1>
    <hr>
     <!--属性和事件绑定-->
    <input type="button" :value="btnTitle" @click="showMsg"></input>
</div>

<script>
    const App = {
        data() {
            return {
                msg: 'hello,vue3!',
                btnTitle: '点我'
            }
        },
        methods:{
            showMsg(){
                alert('点你妹啊!')
            }
        }
    }
    Vue.createApp(App).mount('#app');
</script>

</body>
</html>

2.ref函数用法

在 Vue 2 中,在 v-for 里使用的 ref 属性,this.$refs 会得到一个数组。在 Vue 3 中,不会自动创建数组。要从单个绑定获取多个 ref,需要将 ref 绑定到一个更灵活的函数上 (这是一个新特性):

例如:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/3.1.5/vue.global.prod.min.js"></script>
</head>
<body>
<div id="app">
    <ul>
        <li v-for="c in citys" :ref="initCitys">{{c}}</li>
    </ul>
    <hr>
    <input type="button" @click="changeCity" value="动态改变"/>
</div>

<script>
    const App = {
        data() {
            return {
                msg: 'hello,vue3!',
                citys: ['北京','上海','广州'],
                list:[]
            }
        },
        mounted(){
            console.log(this.list)
        },
        methods: {
            initCitys (el) {
                this.list.push(el)
            },
            changeCity(){
                this.list[0].innerHTML='西安'
            }
        }
    }
    Vue.createApp(App).mount('#app');
</script>

</body>
</html>