当前位置: 代码迷 >> 综合 >> Vue回顾文档--day4
  详细解决方案

Vue回顾文档--day4

热度:84   发布时间:2023-11-26 13:46:00.0

主要复习了vue原生中组件基础的内容,包括组件复用,父子组件的传值,和$emit()的用法

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>组件基础</title>
</head><body><div id="app"><!-- 搭建并调用一个创建的组件 --><button-counter></button-counter>相同组件的复用<!-- 组件的复用 --><button-counter></button-counter><button-counter></button-counter><button-counter></button-counter><br>一个组件的 data 选项必须是一个函数,因此每个实例可以维护一份被返回对象的独立的拷贝,而不会组件复用时相互影响<div class="prop" style="border: 1px solid red; margin: 20px;padding: 20px;">通过Prop 向子组件传递参数<br>Prop 是你可以在组件上注册的一些自定义 attribute。当一个值传递给一个 prop attribute 的时候,它就变成了那个组件实例的一个 property。为了给博文组件传递一个标题,我们可以用一个props 选项将其包含在该组件可接受的 prop 列表中:<br><blog Ptitle="飞飞飞飞"></blog><blog Ptitle="坤坤坤坤"></blog><blog Ptitle="坚坚坚坚"></blog><br>通过父组件的data元素 v-for 遍历复用组件<blog v-for="(item ,index) in titles" v-bind:Ptitle="item.title"></blog>在组件调用时,prop的值要用v-bind绑定(v-bind:Ptitle="item.title"),不像上面一样可以直接写(Ptitle="飞飞飞飞")</div><div class="prop" style="border: 1px solid red; margin: 20px;padding: 20px;">监听子组件事件!!<br>通过子组件放大父组件中内容的大小<br><p :style="{ fontSize: postFontSize + 'px' }">这是父组件中的内容</p>下面是子组件(按钮)<br><!-- 父组件中要接收子组件通过$emit传入的方法名和参数 来触发对应的函数--><sub-event v-on:enlarge="postFontSize++"></sub-event>通过直接的语句实现<br><br><sub-event v-on:enlarge="onEnlargeText"></sub-event>通过父组件中的函数实现<br><br><br>子组件中 给触发事件的元素绑定 $emit('父组件要接收的名称',对应要传递的参数) 来触发定义的事件 <br>父组件中要接收子组件通过$emit传入的方法名和参数(参数名可以用$event接收) 来触发对应的函数</div></div><script src="https://cdn.jsdelivr.net/npm/vue@2"></script><script>//构建一个vue组件--计数器//创建的组件可以被用在任意一个被注册的vue根实例中//vue组件实例 也是vue实例,除了el之外,都和new Vue()有相同的选项//每个注册的组件只能有一个根元素,你可以把里面的内容包含在一个大的div里面Vue.component('button-counter', {
    data: function () {
    return {
    count: 0}},template: ' <button @click="count++">你点了 {
    {count}}次 </button>'})//prop传值Vue.component('blog', {
    props: ['Ptitle'],template: '<p>title: {
    {Ptitle}} </p>'})//$emit传值,父组件监听子组件事件Vue.component('sub-event', {
    template: `<button @click="$emit('enlarge')">px+1</button>`// 子组件中 $emit('父组件要接受的事件名称',对应要传递的参数) 来触发定义的事件})var app = new Vue({
    el: '#app',data: {
    titles: [{
     id: 1, title: "firstTitle" },{
     id: 2, title: 'secondTitle' },{
     id: 3, title: 'thridTitle' }],postFontSize: 19},methods: {
    onEnlargeText() {
    //这个函数的参数会是子组件传递而来的(这里没有写)this.postFontSize++}},})</script>
</body></html>