vue 简介

121 阅读1分钟

使用vue分两种

  • cdn引入
    • 适合改祖传代码
  • 前端工程化
    • .vue文件里写,用命令行编译成html js css等文件,让浏览器可读 两者基础语法是一样的

以下按cdn引入方式讲

html骨架

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <!-- import CSS -->
</head>

<body>
</body>
</html>

cdn引入

<body>后引入

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

使用

body里添加id="app"标签

<div id="app">

</div>

引入vue后,创建vue,el:"#app"要与id="app"对应

<script>
let vm = new Vue({
    el:"#app",
})
</script>

vue常用功能

data

变量放在data里

    data(){
        return {
            a:0
        }
    },

能在html中使用

{{a}}

绑定事件

@click=""

<button @click="a++">加1</button>

将函数放在methods

    methods:{
        add(){
            this.a++
        }
    }

绑定变量

:style

<button @click="changeColor" :style="{color:color}">{{color}}</button>

data中添加

color:"black",

methods中添加

changeColor(){
    this.color = this.color === "black" ? "red":"black"
},

调用函数

<button @click="add">函数加1</button>

判断v-if

<br/>
<button @click="show=!show">{{show?"关闭":"打开"}}</button>
<p v-if="show">现在你看到我了</p>

data中添加

show:true

循环v-for

//html
<div v-for="(item,index) in arr" :key="'arr'+index">
    {{index}}
</div>
<button @click="arr.push('')">数组长度{{arr.length}}</button>

//data
arr:[],

输入v-model

<p>{{ message }}</p>
<input v-model="message">

//data
message:"",

组件

  • 添加组件
<user></user>

//new Vue之前
Vue.component("user",{
    template:`
        <div>
            用户名称:{{name}}
        </div>
    `,
})
  • 传递参数·props
//组件内
props:{
    name:{
        type:String,
        default:""
    },
},

<user name="233"></user>

生命周期

//页面创建时触发
created(){
    console.log(1,"created");
},

使用ui框架element

// 引入css
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">

// 引入js
<script src="https://unpkg.com/element-ui/lib/index.js"></script>

//data
visible: false


// 使用弹窗
<el-button @click="visible = true">Button</el-button>
    <el-dialog :visible.sync="visible" title="Hello world">
      <p>Try Element</p>
    </el-dialog>