怎么在Vue中创建组件和传值

  介绍

怎么在Vue中创建组件和传值?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

<强> # #创建组件的3种方法

#第一种:
, + Vue.extend()函数返回一个组件的构造器,里面包含一个参数,参数是对象,对象里面是一些配置项
+ Vue.component()函数利用Vue.extend()返回的构造器创建一个组件的实例,有两个参数。
参数1:组件名字,参数2:组件构造器

,注意:
,,,,,模板模板中只能有一个根节点

,,,组建的名字采用驼峰命名的话,使用时,就要加上“产生绯闻;;例如:组件名字indexA——祝辞指数;

# #第二种:
, + Vue.component (& # 39; indexB& # 39;,{模板})

# #第三种:
, +通过制定模板创建,在Vue管辖范围之外定义模板

# #总结:
, +先制造一个模板,在创建组件

# #组件中使用指令:
, +在Vue.component()里边,有模板模板,有数据()函数,有方法()方法
+注意:数据()必须是一个个函数。不能使用属性定义;函数里边返回出去一个对象

<强> # #父组件传值给子组件的方法

*先创建好父组件和子组件
*在父组件的模板中,儿子的子组件标签里绑定:属性=父组件需要传递的数据,
, *在子组件的儿子{}中,使用道具来接收父组件传递过来的数据,
, *道具后跟一个数组,数组中是一个个字符串,这些字符串可以当成属性使用,即道具:[& # 39;属性名& # 39;]

, *代码如下:

,,,*

Vue.component(& # 39;父亲# 39;,{   ,,,模板:& # 39;& lt; div> .... & lt; son :名字=癿ySonName"祝辞& lt;/son> & lt;/div> & # 39;   ,,,的数据(){   ,,,,,返回{   ,,,,,,,mySonName: & # 39;小明& # 39;   ,,,,,}   ,,,},   ,,,//子组件   ,,,组件:{   ,,,,,儿子:{   ,,,,,,,道具:[& # 39;名字# 39;],   ,,,,,,,模板:& # 39;…{{名字}}& # 39;   ,,,,,}   ,,,}   })才能

, # #子组件传值给父组件的方法
*先创建好父组件和子组件;

*在子组件方法方法中使用。美元发出()方法,
,,,,*这个方法有两个参数;参数1:需要与父组件交换事件名称,参数2:要传递的数据,

*在父组件模板的儿子标签中使用方法名的传递:

即,@ <代码> tellFatherMyname=癵etMySonName";

*在父组件的方法方法中传入数据参数,这个data=https://www.yisu.com/zixun/子组件传递过来的数据,然后让<代码> mySonName=数据;*

代码如下:,,,,,

& lt; div  id=癮pp"比;   ,,,& lt; father> & lt;/father>   & lt;才能/div>   & lt;才能script>   ,,,Vue.component(& # 39;父亲# 39;,{   ,,,,,模板:“& lt; div>   ,,,,,& lt; p>我的儿子告诉我他叫{{mySonName}} & lt;/p>   ,,,,,& lt; son  @tellFatherMyname=癵etMySonName"祝辞& lt;/son>   ,,,,,& lt;/div>”   ,,,,,数据(){   ,,,,,,,return  {   ,,,,,,,,,mySonName: & # 39; ? ? ? & # 39;   ,,,,,,,}   ,,,,,},   ,,,,,方法:{   ,,,,,,,getMySonName(数据){   ,,,,,,,,,console.log(数据);   ,,,,,,,,,this.mySonName =,数据;   ,,,,,,,}   ,,,,,},   ,,,,,组件:,{   ,,,,,,,儿子:{   ,,,,,,,,,数据(){   ,,,,,,,,,,,return  {   ,,,,,,,,,,,myName : & # 39;小明& # 39;   ,,,,,,,,,,,}   ,,,,,,,,,},   ,,,,,,,,,模板:   ,,,,,,,,,,,,,& lt; button  @click =,“emitMyname"在点击就告诉父亲我叫{{名字}},,,,,,,,,,   ,,,,,,,,,,,,,& lt;/button>”   ,,,,,,,,,//在子组件的方法中使用。发出()美元来传递值;   ,,,,,,,,,//$发出()有2个参数;参数1:需要交换的事件名,参数2:要传递的数据,例,   ,,,,,,,,,,,如:this.name   ,,,,,,,,,方法:{   ,,,,,,,,,,,emitMyname () {   ,,,,,,,,,,,,,,美元发出(& # 39;tellFatherMyname& # 39;, this.myName)   ,,,,,,,,,,,}   ,,,,,,,,,}   ,,,,,,,}   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

怎么在Vue中创建组件和传值