ART*_*Loe 2 vue.js vue-component
我是VueJS和JavaScript的新手,非常感谢您的帮助.
我的方法" greet"不起作用,我不确定为什么.当我点击"更改为栏"按钮时,我收到错误:
[Vue警告]:属性或方法"greet"未在实例上定义,但在呈现期间引用.通过初始化属性,确保此属性在数据选项或基于类的组件中是被动的.请参阅:https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
在发现
Run Code Online (Sandbox Code Playgroud)---> <Chatjsvue> at src\components\vueChartjs\Chatjsvue.vue <App> at src\App.vue <Root>
chartjs.vue
<template src="../../views/chartjshtml/chartsjs.html"></template>
<script>
import LineChart from '@/assets/javascripts/chartjsline'
export default {
components: {
'line-chart': LineChart
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
chartsjs.html
<div class="wrapper">
<div>
<ul>
<li><button v-on:click="greet()">change to bar</button></li>
<li><line-chart></line-chart></li>
</ul>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
chartsjsline.js
import { Line } from 'vue-chartjs'
export default {
extends: Line,
data() {
return {
datacollection: {
//Data to be represented on x-axis
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
datasets: [{
label: 'Activities ChartJS Line',
backgroundColor: '#f87979',
pointBackgroundColor: 'white',
borderWidth: 1,
pointBorderColor: '#249EBF',
//Data to be represented on y-axis
data: [40, 20, 30, 50, 90, 10, 20, 40, 50, 70, 90, 100]
}]
},
//Chart.js options that controls the appearance of the chart
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
},
gridLines: {
display: true
}
}],
xAxes: [{
gridLines: {
display: false
}
}]
},
legend: {
display: true
},
responsive: true,
maintainAspectRatio: false
},
}
},
methods: {
greet() {
alert('hello');
}
},
mounted() {
//renderChart function renders the chart with the datacollection and options object.
this.renderChart(this.datacollection, this.options)
}
}
Run Code Online (Sandbox Code Playgroud)
您的<line-chart>组件(实例LineChart)是组件的子Chatjsvue组件.
子方法仍然绑定到这些实例.
但是,从父组件访问其子组件非常容易,并从那里执行它们的方法:
ref特殊属性保留对子组件的引用:<line-chart ref="myLineChart"></line-chart>this.$refs.myLineChart.this.$refs.myLineChart.greet()工作范例:
Vue.component('chart-js', {
template: '#chartjs',
methods: {
lineChildGreet() {
// Access the child component through $refs.
// Then you can execute its methods.
this.$refs.myLineChart.greet();
},
},
});
Vue.component('line-chart', {
template: '#lineChart',
methods: {
greet() {
alert('hello');
},
},
});
var app = new Vue({
el: '#app',
});Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<chart-js></chart-js>
</div>
<template id="chartjs">
<div class="wrapper">
<div>
<ul>
<li><button v-on:click="lineChildGreet">greet on child component</button></li>
<!-- Keep a REFerence to the child component -->
<li><line-chart ref="myLineChart"></line-chart></li>
</ul>
</div>
</div>
</template>
<template id="lineChart">
<span>LineChart</span>
</template>Run Code Online (Sandbox Code Playgroud)