科学健康资讯 · 内容仅供参考,不替代专业诊疗 联系我们|疾病百科
操作系统

inputbox

2023-05-01 操作系统 本文链接

vue的组件,续前两条

6,监听子组件事件

 

如果需要监听子组件事件,可以使用vue的一些原生方法进行操作,在组件中加入v-on:enlarge-text进行操作:

 

<blog-post...v-on:enlarge-text="postFontSize += 0.1"></blog-post>

 

 

同时在按钮处加入 $emit 方法并传入事件名称来触发一个事件:

<button v-on:click="$emit('enlarge-text')"> Enlarge text </button>

 

有了这个 v-on:enlarge-text="postFontSize += 0.1" 监听器,父级组件就会接收该事件并更新 postFontSize 的值。

 

 

具体实现代码

 

<scriptsrc=https://czxt.haoyundao.net/"https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js">

 

<divid="blog-posts-events-demo">

<div:style="{fontSize:postFontSize+'em'}">

<blog-post

v-for="postinposts"

v-bind:key="Under Construction"

v-bind:post="post"v-on:enlarge-text="postFontSize+=1"

></blog-post>

 

</div>

 

</div>

 

<script>

Vue.component('blog-post',{

props:['post'],

template:`

<divclass="blog-post">

<h3>{{post.title}}</h3>

<buttonv-on:click="$emit('enlarge-text')">

Enlargetext

</button>

<divv-html="post.content"></div>

</div>

`

})

 

newVue({

el:'#blog-posts-events-demo',

data:{

posts:[

{id:1,title:'MyjourneywithVue'},

{id:2,title:'BloggingwithVue'},

{id:3,title:'WhyVueissofun'}

],

postFontSize:1

}

})

</script>

 

可以事件来抛出一个值,让点击后的字体放大到想要的效果。

 

<buttonv-on:click="$emit('enlarge-text', 0.1)"> Enlarge text </button>

 

<blog-post...v-on:enlarge-text="postFontSize += $event"></blog-post>

 

在组件中使用v-model,设计代码如下:

 

Vue.component('custom-input', {

  props: ['value'],

  template: `

    <input

      v-bind:value=https://czxt.haoyundao.net/"value"

      v-on:input="$emit('input', $event.target.value)"

    >

  `})

 

现在 v-model 就应该可以在这个组件上完美地工作起来了:

 

<custom-input  v-model="searchText"></custom-input>

 

 

7,通过插槽分发内容

 

Vue.component('alert-box', { template: `

    <div class="demo-alert-box">

      <strong>Error!</strong>

      <slot></slot>

    </div>

  ` })

 

 

8,动态组件

 

<!-- 组件会在 `currentTabComponent` 改变时改变 -->

<componentv-bind:is="currentTabComponent"></component>

本文内容仅供健康科普参考,不能替代专业医疗诊断和治疗建议。如有身体不适,请及时就医并遵从医师指导。

相关阅读