【阿里云】各类产品,精心挑选的热门优惠云产品,总有一款适合你的业务形态【腾讯云】爆款2核2G云服务器首年40元,企业首购最高获赠300元京东卡

Vue3 基础语法

一、语法

  • 每个 vue 文件,分三部分
    • <template></template> 对应 html 代码
    • <script></script> 对应 js 代码
    • <style></style> 对应 css 代码

1、插值、数据绑定

  • 使用双大括号 {{}} 进行插值、数据绑定
  • defineComponent 函数,只是对 setup 函数进行封装,返回 options 的对象。
  • defineComponent 最重要的是:在 TypeScript 下,给予了组件 正确的参数类型推断。
# 1、单独写双大括号,是没有数据的,因为数据是从js里来的
# 1.1、在template标签里,必须有个最外层的标签
<template>
    <div>我是:{{ ouyangke }}</div>
</template>

# 2、js 返回 ouyangke 这个数据
# 2.1、ouyangke相当于下标,"欧阳克"相当于值
# 2.2、export default(es6默认导出) 一个文件只能有一个
# 2.3、data(){},交互数据,也是M层。return{},数据要返回。
<script>
export default {
    data() {
        return {
            ouyangke: "欧阳克"
        };
    }
};
</script>

2、基本运算

<template>
    <div>
        <div>{{ ouyangke+zhutianpeng }}</div>
        <div>{{ num1+num2 }}</div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            ouyangke: "欧阳克",
            zhutianpeng : "朱天蓬",
            num1 : 20,
            num2 : 10
        };
    }
};
</script>

3、方法

<template>
    <div>
        <div>{{ ouyangke+zhutianpeng }}</div>
        <div>{{ num1+num2 }}</div>
        <div>{{ fun() }}</div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            ouyangke: "欧阳克",
            zhutianpeng : "朱天蓬",
            num1 : 20,
            num2 : 10
        };
    },
    methods:{
        fun(){
            console.log('方法1');
            // this 调用data里的数据
            console.log(this.ouyangke);
            return "方法1";
        },
        fun1(){
            console.log('方法2');
            // this 调用metods里的方法
            this.fun();
        }
    }
};
</script>

4、三元表达式

<template>
    <div>
        <div>{{ boor ? '真' : '假' }}</div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            boor: true
        };
    }
};
</script>

5、错误的写法

<template>
    <div>
        <!-- 这是一个语句,而非表达式 -->
        <div>{{ var a = 1 }}</div>

        <!-- 条件控制也不支持,请使用三元表达式 -->
        <div>{{ if (boor) { return '真' } }}</div>
    </div>
</template>

6、export defaultoption 构造(选项)

构造(选项)描述
name绑定标签名
data交互数据
methodsjs方法
computed计算属性
components组件
props组件之间数据交互
setup组合API

二、指令

指令描述
v-model指令在表单 <input><textarea><select> 元素上创建双向数据绑定
v-once只渲染元素和组件一次
v-text更新元素的 textContent,跟插值效果一样
v-html更新元素的 innerHTML
v-pre跳过这个元素和它的子元素的编译过程,示原始 Mustache 标签
v-bind:动态地绑定属性
# 1、`v-model` 指令在表单 `<input>`、`<textarea>` 及 `<select>` 元素上创建双向数据绑定
<template>
    <div>
        <div>{{ ouyangke }}</div>
        <input type="text" v-model:value="ouyangke">
    </div>
</template>
<script>
export default {
    data() {
        return {
            ouyangke: "欧阳克"
        };
    }
};
</script>

# 2、`v-once` 只渲染元素和组件一次
<template>
    <div>
        <div>{{ ouyangke }}</div>
        <input type="text" v-model="ouyangke">
        <div v-once>{{ ouyangke }}</div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            ouyangke: "欧阳克"
        };
    }
};
</script>

# 3、`v-text` 更新元素的 `textContent`,跟插值效果一样
<template>
    <div>
        <div>{{ ouyangke }}</div>
        <input type="text" v-model="ouyangke">
        <div v-text="ouyangke"></div>
        <div v-text="ouyangke">这里不能在写文字</div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            ouyangke: "欧阳克"
        };
    }
};
</script>

# 4、`v-html` 更新元素的 `innerHTML`
# 4.1、注意:网页中动态渲染任意的HTML可能非常危险,很容易导致XSS攻击,最好对可信的内容使用v-html指令,绝对不能让用户输入内容使用这个指令
<template>
    <div>
        <div>{{ htmlcode }}</div>
        <div v-html="htmlcode"></div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            htmlcode: "<h1 style='color:red;'>欧阳克</h1>"
        };
    }
};
</script>

# 5、`v-pre` 跳过这个元素和它的子元素的编译过程,示原始 `Mustache` 标签
<template>
    <div>
        <div v-pre>{{ htmlcode }}</div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            htmlcode: "<h1 style='color:red;'>欧阳克</h1>"
        };
    }
};
</script>

# 6、`v-bind` 动态地绑定属性
<template>
    <div>
        <a href="https://www.php.cn" title="php中文网">{{ name }}</a>
        
        <a href="https://www.php.cn" title="{{name}}">{{ name }}</a>
        
        <a href="https://www.php.cn" v-bind:title="name">{{ name }}</a>
        
        // 语法糖,缩写 :
        <a :href="url" :title="name">{{ name }}</a>
    </div>
</template>
<script>
export default {
    data() {
        return {
            name: "php中文网",
            url : "https://www.php.cn"
        };
    }
};
</script>
# 6.1、常用的绑定style和class属性,四种用法(字符串、数组、对象、方法)
<template>
    <div>
        // 字符串变量写法
        <div style="color: red; font-size: 24px" :style="style">{{ name }}</div>
        // 数组写法
        <div style="color: red; font-size: 24px" :style="[arr1, arr2, 'background:#33aa33']">{{ name }}</div>
        // 对象写法
        <div style="color: red; font-size: 24px" :style="{width:obj,height:obj,background:'#33aa33'}">{{ name }}</div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            name: "php中文网",
            style: "width:200px;height:200px;background:#33aa33",
            arr1:"width:200px",
            arr2:"height:200px",
            obj:"200px"
        };
    }
};
</script>
# 6.2、class属性,使用
<template>
    <div>
        // 字符串变量写法
        <div class="div" :class="class1">{{ name }}</div>
        // 单引号、使用class名,跟之前写到class里没区别
        <div class="div" :class="['fs24']">{{ name }}</div>
        // 对象写法(用的最多的):class名作为下标
        <div class="div" :class="{fs24:true}">{{ name }}</div>
        // 配合点击事件,可以显示隐藏
        <button @click="show = !show">点击</button>
        <div class="div hide" :class="{ show: show }">{{ name }}</div>
        // 混合使用
        <div class="div hide" :class="[{ show: show },'fs24']">{{ name }}</div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            name: "php中文网",
            class1: "fs24",
            show: true,
        };
    }
};
</script>
<style lang="scss">
.div {
    width: 200px;
    height: 200px;
    background: #33aa33;
}
.fs24 {
    font-size: 24px;
}
.hide {
    display: none;
}
.show {
    display: block;
}
</style>

三、计算属性

  • 模板内的表达式非常便利,但是设计它们的初衷是用于简单运算的。在模板中放入太多的逻辑会让模板过重且难以维护,所以,对于任何包含响应式数据的复杂逻辑,都应该使用计算属性。
# 1、老版本 连接字符串方式
<template>
    // 第一种方式
    <div>{{ ouyangke}}-{{phpcn}}</div>
    // 第二种方式
    <div>{{ ouyangke + '-' + phpcn}}</div>
    // 第三种方式
    <div>{{fun()}}</div>
</template>
<script>
export default {
    data() {
        return {
            ouyangke: "欧阳克",
            phpcn : "php中文网"
        };
    },
    methods : {
        fun(){
            return this.ouyangke + '-' + this.phpcn
        }
    }
};
</script>

# 2、computed 计算属性
<template>
    <div>{{ handle }}</div>
</template>
<script>
export default {
    data() {
        return {
            ouyangke: "欧阳克",
            phpcn : "php中文网"
        };
    },
    computed : {
        handle(){
            return this.ouyangke + "-" + this.phpcn;
        },
        // 两种写法一样的
        handle(){
            get(){
                return this.ouyangke + "-" + this.phpcn;
            }
        }
    }
};
</script>
# 2.1、set方法
<template>
    <div>{{ handle }}</div>
    <input type="text" v-model="ouyangke" />
    <input type="text" v-model="handle" />
</template>
<script>
export default {
    data() {
        return {
            ouyangke: "欧阳克",
            phpcn : "php中文网"
        };
    },
    computed : {
        handle : {
            get(){
                return this.ouyangke + "-" + this.phpcn;
            },
            set(v){
                console.log(v);
            }
        }
    }
};
</script>

# 3、缓存机制:计算属性只会执行一次,方法会执行多次
<template>
    <div>{{fun()}}</div>
    <div>{{ handle }}</div>
    <div>{{fun()}}</div>
    <div>{{ handle }}</div>
    <div>{{fun()}}</div>
    <div>{{ handle }}</div>
    <input v-model="ouyangke" />
</template>
<script>
export default {
    data() {
        return {
            ouyangke: "欧阳克",
            phpcn : "php中文网"
        };
    },
    methods : {
        fun(){
            console.log('方法:掉用几次、执行几次');
            return this.ouyangke + '-' + this.phpcn
        }
    },
    computed : {
        handle : {
            get(){
                console.log('计算属性、执行一次');
                return this.ouyangke + "-" + this.phpcn;
            }
        }
    }
};
</script>

四、指令:事件监听

# 1、调用方法,语法糖:@
<template>
    <div>
        <button v-on:click="fun()">{{ button }}</button>
        <button @click="fun()">{{ button }}</button>
        // 也可以使用简单的语句
        <button @click="show = !show">{{ button }}</button>
        <div class="div hide" :class="{ show: show }">{{ button }}</div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            button: "按钮",
            show: true
        };
    },
    methods: {
        fun() {
            alert(111);
        }
    }
};
</script>
<style lang="scss">
.hide {
    display: none;
}
.show {
    display: block;
}
</style>

# 2、传值
<template>
    <div>
        <button @click="fun('ouyangke')">{{ button }}</button>
    </div>
</template>
<script>
export default {
    data() {
        return {
            button: "按钮",
            show: true
        };
    },
    methods: {
        fun(name) {
            alert(name);
        }
    }
};
</script>
  • v-on 事件修饰符号
    • .stop 阻止事件冒泡
    • .self 当事件在该元素本身触发时才会执行
    • .capture 添加事件监听器,优先执行该事件
    • .prevent 阻止默认事件,比如 a 标签的跳转
    • .once 事件只触发一次
# 3、(.stop) 三层事件,点击第三层,上面2层也会执行。 增加.stop会防止冒泡事件
<template>
    <div>
        <div @click="one()">
            第一层
            <div @click="two()">
                第二层
                <div @click.stop="three()">第三层</div>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            button: "按钮",
            show: true,
        };
    },
    methods: {
        one() {
            console.log("第一层");
        },
        two() {
            console.log("第二层");
        },
        three() {
            console.log("第三层");
        }
    }
};
</script>
# 3.1、(.self) 点击第二层和第三层,都不会执行第一层。必须点击它自己才会处罚。当事件在该元素本身触发时才会执行
<template>
    <div>
        <div @click.self="one()">
            第一层
            <div @click="two()">
                第二层
                <div @click="three()">第三层</div>
            </div>
        </div>
    </div>
</template>
# 3.2、(.capture) 点击第二层和第三层,会先执行第一层。添加事件监听器,优先执行该事件
<template>
    <div>
        <div @click.capture="one()">
            第一层
            <div @click="two()">
                第二层
                <div @click="three()">第三层</div>
            </div>
        </div>
    </div>
</template>
# 3.3、(.prevent) 阻止a标签的默认事件
<template>
    <div>
        <a href="http://www.php.cn" @click.prevent="one()">php中文网</a>
    </div>
</template>
# 3.4、(.once) 事件只触发一次,第二次点击就执行a标签默认事件
<template>
    <div>
        <a href="http://www.php.cn" @click.prevent.once="one()">php中文网</a>
    </div>
</template>

# 4、执行多个事件
<template>
    <div>
        <a href="http://www.php.cn" @click="one(),two()">php中文网</a>
    </div>
</template>

# 5、其他事件(mouseover鼠标移到标签) (mouseout鼠标移开标签)
<template>
    <div>
        <a href="http://www.php.cn" @mouseover="one()" @mouseout="two()">php中文网</a>
    </div>
</template>

五、流程控制

# 1、`v-if`
# `v-if` “真正”的条件渲染,因为它会确保在切换过程中,条件块内的事件监听器和子组件适当地被销毁和重建
# `v-if` 是惰性的:如果在初始渲染时条件为假,则什么也不做——直到条件第一次变为真时,才会开始渲染条件块
# v-if 切换开销更高,运行条件很少改变,使用v-if
<template>
    <div>
        <button @click="fun()">按钮</button>
        <div v-if="bool">欧阳克</div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            bool: false,
        };
    },
    methods: {
        fun() {
            return (this.bool = !this.bool);
        }
    }
};
</script>

# 2、v-show 不管初始条件是什么,元素总是会被渲染,并且只是简单地基于 CSS 进行切换
# v-show 初始渲染开销更高,如果需要非常频繁切换,就使用v-show
<template>
    <div>
        <button @click="fun()">按钮</button>
        <div v-show="bool">欧阳克</div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            bool: false
        };
    },
    methods: {
        fun() {
            return (this.bool = !this.bool);
        }
    }
};
</script>

# 3、`v-else`
<template>
    <div>
        <button @click="fun()">按钮</button>
        <div v-if="bool">欧阳克</div>
        <div v-else>朱天蓬</div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            bool: false
        };
    },
    methods: {
        fun() {
            return (this.bool = !this.bool);
        }
    }
};
</script>

# 4、`v-else-if`
<template>
    <div>
        <button @click="fun()">按钮</button>
        <div v-if="bool == 1">欧阳克</div>
        <div v-else-if="bool == 2">朱老师</div>
        <div v-else>灭绝师太</div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            bool: 1
        };
    },
    methods: {
        fun() {
            if (this.bool == 2) {
                this.bool = 0;
            } else {
                this.bool += 1;
            }
            return this.bool;
        }
    }
};
</script>

六、循环遍历 v-for

1、遍历数组

<template>
    <div>
        // 循环数组
        <div v-for="item in phpcn" v-bind:key="item">{{ item }}</div>
        // 循环数组,带下标key
        <div v-for="(item, index) in phpcn" v-bind:key="item">
            {{ item }} - {{ index }}
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            phpcn : ['欧阳克','朱天蓬','灭绝师太','西门大官人']
        };
    }
};
</script>

2、遍历对象

<template>
    <div>
        <div v-for="item in phpcn" :key="item">{{ item }}</div>
        <div v-for="(item, index, key) in phpcn" :key="item">
            {{ item }} - {{ index }} - {{ key }}
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            phpcn: {
                ouyangke: "欧阳克",
                tianpeng: "朱天蓬",
                miejue: "灭绝师太",
                ximen: "西门大官人",
            }
        };
    }
};
</script>

3、混编,json 数据

<template>
    <div>
        <div v-for="(item, index) in phpcn" :key="item">
            {{ item.name }} - {{ item.age }} - {{ index }}
        </div>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                phpcn: [
                    {
                        name: "欧阳克",
                        age: "38岁",
                    },
                    {
                        name: "朱天蓬",
                        age: "48岁",
                    },
                    {
                        name: "灭绝师太",
                        age: "18岁",
                    },
                    {
                        name: "西门大官人",
                        age: "28岁",
                    }
                ]
            };
        }
    };
</script>


# 4、嵌套
<template>
    <div>
        <div v-for="item in phpcn" :key="item">
            <div v-for="item2 in item" :key="item2">
                {{ item2 }}
            </div>
        </div>
    </div>
</template>


# 5、`:key=`唯一标识,可以是item里的id、index等,主要为了高速提供虚拟Dom速度
# HTML的Dom树,
<template>
    <div>
        <div>
            <input type="text" v-model="newid" />
            <input type="text" v-model="name" />
            <input type="text" v-model="age" />
            <button @click="add()">添加</button>
        </div>
        <ul>
            // 如果没有 :key ,选择复选框后,添加人员,复选框会移动
            <li v-for="(item, index) in teacher">
                <input type="checkbox" /> {{ index }} - {{ item.name }} -
                {{ item.age }} - {{ item.id }}
            </li>
            <li v-for="(item, index) in teacher" :key="item.id">
                <input type="checkbox" /> {{ index }} - {{ item.name }} -
                {{ item.age }} - {{ item.id }}
            </li>
        </ul>
    </div>
</template>
<script>
export default {
    data() {
        return {
            newid: "",
            name: "",
            age: "",
            teacher: [
                {
                    id: 1,
                    name: "欧阳克",
                    age: "38岁",
                },
                {
                    id: 2,
                    name: "朱天蓬",
                    age: "48岁",
                },
                {
                    id: 3,
                    name: "灭绝师太",
                    age: "18岁",
                },
                {
                    id: 4,
                    name: "西门大官人",
                    age: "28岁",
                }
            ]
        };
    },
    methods: {
        add() {
            this.teacher.unshift({
                id: this.newid,
                name: this.name,
                age: this.age + "岁",
            });
            this.newid = "";
            this.name = "";
            this.age = "";
        }
    }
};
</script>

七、v-model 表单数据绑定

1、input 输入框修饰符

  • v-model.lazy 懒加载
  • v-model.number 设置数据类型
  • v-model.trim 去除输入框头部的空格
# 1、`v-model.lazy` 懒加载,按回车、或者光标离开输入框,才会执行
# 2、`v-model.number` 设置数据类型,开始输入数字,后面在输入其他符号,就会被屏蔽
# 3、`v-model.trim` 去除输入框头部的空格,点击完成后,输出的字符串,两边空格就去掉了
<template>
    <div>
        <div>{{ ouyangke }}</div>
        <input type="text" v-model.lazy="ouyangke" />
        <input type="text" v-model.number="ouyangke" />
        <input type="text" v-model.trim="ouyangke" />
        <button @click="fun()">按钮</button>
    </div>
</template>
<script>
export default {
    data() {
        return {
            ouyangke: "欧阳克"
        };
    },
    methods: {
        fun() {
            console.log(this.ouyangke);
        }
    }
};
</script>

2、表单使用

<template>
    <div>
        // 单选框
        <input type="radio" v-model="sex" value="1" /><input type="radio" v-model="sex" value="2" /><br/>

        // 多选框:单个可以用 真true、假false
        <input type="checkbox" v-model="is" /> 同意协议
        <br/>

        // 多选框:值要存为数组
        <input type="checkbox" value="ouyangke" v-model="name" /> 欧阳克 <br/>
        <input type="checkbox" value="zhutianpeng" v-model="name" /> 朱天蓬 <br/>
        <input type="checkbox" value="miejueshitai" v-model="name" /> 灭绝师太<br/>
        <input type="checkbox" value="ximendaguanren" v-model="name" /> 西门大官人<br/>
        {{ name }}
        <br/>

        // 下拉框:值要存为普通值
        <select name="names" v-model="names">
            <option value="">-- 请选择 --</option>
            <option value="ouyangke">欧阳克</option>
            <option value="zhutianpeng">朱天蓬</option>
            <option value="miejueshitai">灭绝师太</option>
            <option value="ximendaguanren">西门大官人</option>
        </select>
        <br/>
        {{ names }}
        <br/>

        // 展开下拉框:值要存为数组
        <select name="name" size="5" multiple v-model="name">
            <option value="">-- 请选择 --</option>
            <option value="ouyangke">欧阳克</option>
            <option value="zhutianpeng">朱天蓬</option>
            <option value="miejueshitai">灭绝师太</option>
            <option value="ximendaguanren">西门大官人</option>
        </select>
        <br/>
        {{ name }}
    </div>
</template>
<script>
export default {
    data() {
        return {
            sex: 2,
            is: false,
            name: ["ouyangke"],
            names: "",
        };
    }
};
</script>