vue通过引入js标签的方式在HTML上的组件写法,父子组件数据传递

简介

此页面可以直接复制运行,包含以下应用:

  1. Vue slot插槽使用
  2. Vue v-model使用
  3. Vue props使用
  4. 父子组件数据传递
  5. element-ui使用
  6. HTML方式注册子组件,可以将子组件数据写在一个js文件中,用标签引入,然后将子组件对象置入components

Live Demo 在线示例

Live Demo

提示

不建议用HTML模式开发项目,建议使用vue-cli3创建项目,使用单文件组件模式开发
Vue cli3

代码


<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>Titletitle>
  <script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js">script>
  <script src="https://cdn.bootcss.com/element-ui/2.10.1/index.js">script>
  <link href="https://cdn.bootcss.com/element-ui/2.10.1/theme-chalk/index.css" rel="stylesheet">
  <style>
    #app{
      display: flex;
      justify-content: space-between;
    }
    .parent, .child{
      width: 45%;
    }
    .el-card{
      height: 100%;
    }
  style>
head>
<body>
<div id="app">
  <div class="parent">
    <el-card>
      <div slot="header">
        <span>父组件span>
      div>
      <el-input v-model="ParentMsg">el-input>
      <el-button type="primary" @click="changeChild" style="margin-top: 30px">改变子组件的msgel-button>
    el-card>

  div>
  <div class="child">
    <el-card>
      <div slot="header">
        <span>子组件span>
      div>
      <child1 v-show="display" :parent-msg="childMsg">child1>
      <child2 @change-data-from-child="changeParent">child2>
    el-card>
  div>
div>
<script>
  new Vue({
    el: '#app',
    data(){
      return {
        display:true,
        ParentMsg:"Hello This is Parent",
        childMsg: 'Hello, 我来自父组件的数据'
      }
    },
    methods: {
      changeParent(data){
        this.ParentMsg = data
      },
      changeChild(){
        this.childMsg = '我被父组件改变了'
      }
    },
    components: {
      'child1': {
        props: { //定义子组件的prop,用于父组件传递数据到子组件
          parentMsg: {
            type: String,
            default: ''
          }
        },
        template: '
\n' + '

{{msg}}

\n'
+ '

{{parentMsg}}

\n'
+ ' 切换子组件1中的信息显示隐藏\n' + '
'
, data() {//Vue中component的data必须通过function() return return { msg: 'This is a Child Component1!', msgDisplay: true } }, methods: { toggleMsgDisplay() { this.msgDisplay = !this.msgDisplay } } }, 'child2':{ template:"我是子组件2按钮,点击改变父组件内容", data () { return { msg:"点击了子组件2按钮" } }, methods:{ changeParentData () { this.$emit('change-data-from-child', '我来自是子组件2') //事件传递用kebab-case风格 } } } }, })
script> body> html>

你可能感兴趣的:(vue)