5

Vue的入门学习_13302531的技术博客_51CTO博客

 9 months ago
source link: https://blog.51cto.com/u_13312531/6866166
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Vue的入门学习

精选 原创

vue的安装请参考其他文章,一般有三种方式,第一种方式是下载vue.js,在页面通过<script>标签引用。第二种方式是直接使用vue的CDN版本。第三种方式是使用NPM安装的方法。

二、生命周期

beforeCreate:创建前,数据观测和初始化事件还没有开始。

created:创建后,完成数据观测,属性和方法的运算,初始化事件。

beforeMount:载入前,在挂载之前被调用,相关的render函数被调用,实例已完成以下配置:编译模板,data里面的数据和模板生成html。

mounted:载入后,在el被新创建的vm.$el替换,并挂载到实例上去之后调用。

beforeUpdate:更新前,在数据更新之前调用。

updated:更新后,数据更改后调用。

beforeDestroy:销毁前,在实例销毁之前调用。

destroyed:销毁后,在实例销毁之后调用。

三、语法学习

{{变量名/对象.属性名}}

插值表达式,把vue中定义的数据显示在页面上

v-text

把数据当作纯文本展示

v-html

遇到html标签,会正常解析

v-model

数据双向绑定,当数据发生变化的时候,页面会自动刷新,页面发生变化的时候,数据也会自动变化

事件绑定,可以给页面元素绑定事件

v-on:click等

v-for

v-if/v-show

条件判断,v-if条件不满足时,元素不会存在,v-show条件不满足时,元素隐藏

v-bind

v-bind的作用和插值表达式差不多,只不过v-bind的主要作用用于动态设置标签的属性值

watch

watch可以监听简单属性值及其对象中属性值的变化

computed

计算属性,就是一个提前定义好的方法,该方法可以看作说一个特殊的值,可以在插值表达式中使用

四、语法使用

1.插值表达式{{变量名/对象.属性名}}

<template>
  <div class="hello">
    {{msg}}
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg:'hello'
    }
  },
  methods:{
  },
  computed:{

  },
  watch:{

  },
  components:{
  }
}
</script>

<style scoped>
</style>
Vue的入门学习_axios

2.显示数据(v-text和v-html)

<template>
  <div class="hello">
    <h2 v-text="msg"></h2>
    <h2 v-html="htmldata"></h2>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      msg: 'hello',
      htmldata: '<h1>hello</h1>'
    }
  },
  methods: {},
  computed: {},
  watch: {},
  components: {}
}
</script>

<style scoped>
</style>
Vue的入门学习_Vue_02

3.判断数据(v-if和v-show)

<template>
  <div class="hello">
   <span v-if="show">v-if</span>
    <span v-show="show">v-show</span>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
     show:false
    }
  },
  methods: {},
  computed: {},
  watch: {},
  components: {}
}
</script>

<style scoped>
</style>

v-show条件不满足时会隐藏数据,v-if条件不满足时,元素不会存在。

Vue的入门学习_axios_03

4.循环遍历(v-for)

v-for="item in items"
v-for="(item,index) in items"

items:要迭代的数组

item:存储数组元素的变量名

index:迭代到当前元素的索引,从0开始

<template>
  <div class="hello">
    <ul>
      <li v-for="(item,index) in list">
        {{ index }}--{{ item }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      list: ['a', 'b', 'c']
    }
  },
  methods: {},
  computed: {},
  watch: {},
  components: {}
}
</script>

<style scoped>
</style>
Vue的入门学习_Vue语法_04

5.数据双向绑定(v-model)

绑定文本框:

<template>
  <div class="hello">
    <input type="text" v-model="message"/>
    {{ message }}
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      message: ''
    }
  },
  methods: {},
  computed: {},
  watch: {},
  components: {}
}
</script>

<style scoped>
</style>
Vue的入门学习_axios_05

绑定单个复选框

<template>
  <div class="hello">
    <input type="checkbox" v-model="agree"/>同意
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      agree: true
    }
  },
  methods: {},
  computed: {},
  watch: {},
  components: {}
}
</script>

<style scoped>
</style>

Vue的入门学习_axios_06

绑定多个复选框

<template>
  <div class="hello">
    <input type="checkbox" value="football" v-model="sport"/>足球<br/>
    <input type="checkbox" value="basketball" v-model="sport"/>篮球<br/>
    <input type="checkbox" value="volleyball" v-model="sport"/>排球<br/>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      sport: ['football','basketball']
    }
  },
  methods: {},
  computed: {},
  watch: {},
  components: {}
}
</script>

<style scoped>
</style>
Vue的入门学习_axios_07

6.事件处理(v-on)

<button v-on:click='函数名'></button>
<!--简化语法-->
<button @click='函数名'></button>
<template>
  <div class="hello">
    <button @click="show">click</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {}
  },
  methods: {
    show: function () {
      alert('hello')
    }
  },
  computed: {},
  watch: {},
  components: {}
}
</script>

<style scoped>
</style>

我们的按钮绑定一个事件弹出显示框。

Vue的入门学习_Vue_08

事件修饰符:

.stop:阻止事件冒泡,就是当前元素发生事件,当前元素的父元素不发生该事件
.prevent:阻止默认事件发生
.capture:使用事件捕获模式,主动获取子元素发生事件,把获取到的事件当作自己的事件执行
.self:只有元素自身触发事件才执行
.once:只执行一次

7.显示数据(v-bind)

v-bind的作用和插值表达式差不多, 只不过, v-bind主要用于动态设置标签的属性值。

<标签名 v-bind:标签属性名="vue实例属性名"/>
<标签名 :标签属性名="vue实例属性名"/>
<template>
  <div class="hello">
    <input type="button" v-bind:value="msg"/>
    <input type="button" :value="msg"/>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      msg: '按钮'
    }
  },
  methods: {},
  computed: {},
  watch: {},
  components: {}
}
</script>

<style scoped>
</style>
Vue的入门学习_Vue_09

五、其他语法

1.计算属性

计算属性就是一个提前定义好的方法,该方法可以看作一个特殊的值,可以在插值表达式中使用。

在computed中定义计算属性。

<template>
  <div class="hello">
    <input type="button" :value="msg"/>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {}
  },
  methods: {},
  computed: {
    msg: function () {
      return '我是按钮';
    }
  },
  watch: {},
  components: {}
}
</script>

<style scoped>
</style>

2.watch监控

watch可以监听属性值及其对象中属性值的变化

<template>
  <div class="hello">
    <input type="text" :value="msg"/>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      msg: 'hello'
    }
  },
  methods: {},
  computed: {},
  watch: {
    msg(newValue, oldValue) {
      console.log("新值:" + newValue + ",旧值:" + oldValue)
    }
  },
  components: {}
}
</script>

<style scoped>
</style>
Vue的入门学习_Vue语法_10

六、自定义组件

<template>
  <div class="hello">
    <my-template :message="msg"></my-template>
  </div>
</template>

<script>
// 定义组件
const myTemplate = {
  // 定义组件的模板
  template: "<button @click='num++'>点击了{{num}}次--{{message}}</button>",
  props: {
    // 定义属性
    message: ''
  },
  // 定义组件中使用到的数据属性
  data() {
    return {
      num: 0
    }
  }
}
export default {
  name: 'HelloWorld',
  data() {
    return {
      msg: 'hello'
    }
  },
  methods: {},
  computed: {},
  watch: {},
  // 局部注册组件:只能在当前vue实例中使用
  components: {
    // 组件名称:具体组件
    myTemplate: myTemplate
  }
}
</script>

<style scoped>
</style>
Vue的入门学习_axios_11

注意:

  1. 组件的模版中, 只能书写一个根标签
  2. 组件的定义必须放在Vue创建对象之前, 否则报错

七、axios请求

语法:

axios是一个基于 promise 的 HTTP 库, 主要用于:发送异步请求获取数据。

常见的方法:

 axios(config)

 axios.get(url, [config])

 axios.post(url, [data])

发送数据config常用参数:

{
	url: '请求的服务器',
	method: '请求方式',
	// GET请求参数
	params: {
		参数名: 参数值
	},
	// POST请求参数
	data:{
		参数名: 参数值
	},
// 响应数据格式,默认json
	responseType: 'json'
}

响应数据常用参数:

{
    data: {},		//真正的响应数据(响应体)
    status: 200,	//响应状态码
    statusText: 'OK',	 //响应状态描述
    headers: {},	//响应头
    config: {}		//其他配置信息
}

1.创建SpringBoot项目,并书写一个测试请求

package com.example.vuespringboot.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author qx
 * @date 2023/7/26
 * @des
 */
@CrossOrigin(origins = "http://localhost:8080")
@RestController
public class IndexController {

    @GetMapping("/showData")
    public String showData() {
        return "hello from spring boot";
    }
}

@CrossOrigin(origins = "http://localhost:8080")这个注解可以处理跨域的问题。来自8080端口的网页请求可以请求这个后台接口。

<template>
  <div class="hello">
    <button @click="getData">获取数据</button>
    <br/>
    {{ msg }}
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'HelloWorld',
  data() {
    return {
      msg: ''
    }
  },
  methods: {
    getData: function () {
      var that = this
      axios.get('http://localhost:8081/showData')
        .then(function (resp) {
          console.log(resp)
          that.msg = resp.data
        }).catch(function (error) {
      })
    }
  },
  computed: {},
  watch: {},
  components: {}
}
</script>

<style scoped>
</style>
Vue的入门学习_Vue语法_12

POST请求:

我们在服务端创建一个接受客户端请求数据的接口

  @PostMapping("/form")
    public Map<String, String> receiveFormData(String username, String password) {
        Map<String, String> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        map.put("code", "200");
        return map;
    }

然后我们在前端编写一个提交表单的页面

<template>
  <div class="hello">
    <form method="post">
      <input type="text" placeholder="请输入用户名" v-model="formData.username"/>
      <br/>
      <br/>
      <input type="password" placeholder="请输入密码" v-model="formData.password"/>
    </form>
    <button @click="submit">提交</button>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'HelloWorld',
  data() {
    return {
      formData: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    submit: function () {
      // 封装请求参数
      let data = new FormData();
      for (var key in this.formData) {
        data.append(key, this.formData[key]);
      }
      axios({
        method: 'post',
        url: 'http://localhost:8081/form',
        headers: {
          "Content-Type": "multipart/form-data"
        },
        data: data
      }).then(function (resp) {
        console.log(resp);
      }).catch(function (error) {
      })
    }
  },
  computed: {},
  watch: {},
  components: {}
}
</script>

<style scoped>
</style>
Vue的入门学习_Vue语法_13

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK