Vue组件传参

component( ) 自定义组件时经常会用到参数,主要有两种情况:父向子传参、子向父传参。

父子传参:

在父子传参中需要用到的是 component 中的 props 属性,props 是一个数组,包含了父级组件传来的参数。
下面这个例子中,定义了一个 user 组件,用来显示一个名字的 a 标签,当点击时跳转到该名字的页面。用法如下:


<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>proptitle>
head>
<body>
<div id="app">
    <user username="Talon">user>
div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js">script>
<script type="text/javascript">
    Vue.component('user', {
        template: '{{username}}',
        props: ['username'],
    })
    new Vue({
        el: '#app'
    })
script>
body>
html>

子父传参:

上面实现了父子之间的传参,现在实现以下子父之间的传参。先自定义两个组件 balance 和 show,用来显示余额。在 balance 组件的模板中调用 show 组件,然后将参数在 show 组件中传到 balance 中。


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demotitle>
head>
<body>
<div id="app">
    <balance>balance>
div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js">script>
<script type="text/javascript">
    Vue.component('balance', {
        template: `
        
您的余额:{{money}}
`
, data: function () { return{ show: false, money: 0, } }, methods: { show_balance: function (data) { this.show = true; this.money = data; } } }); Vue.component('show', { template: '', methods: { onClick:function () { this.$emit('show-balance', 100); } } }); new Vue({ el: '#app' })
script> body> html>

你可能感兴趣的:(前端,Vue)