Is there any way to render html element with custom properties inside template tag using javascript functions?
Example what I try to achieve:
<template>
<div class="test">
{{ testFunction(param1,param2,param3) }}
</div>
</template>
<script>
export default {
....
methods: {
testFunction(param1,param2,param3) {
return `<button #click="function()">Click</button>`;
}
}
};
</script>
Directly you will get interpolated html, like this
<button #click="function()">Click</button>
Even if you fix it using the v-html directive to output raw HTML the button will still not work.
The right way is to use Render Functions like this:
const myComponent3 = {
setup(props) {
return () => h('button',
{
onClick(event) {
alert('Click');
}
},
'Click Me!'
)
}
}
Here is the playground with samples:
const { createApp, h } = Vue;
const myComponent1 = {
template: '#my-component',
methods: {
testFunction(par1) {
return `<button #click="function()">Click</button>`;
}
}
}
const myComponent2 = {
template: '<div v-html="rawHTML()"></div>',
methods: {
myClick() {
alert('Click');
},
rawHTML(par1) {
return '<button #click="myClick()">Click</button>';
}
}
}
const myComponent3 = {
setup(props) {
return () => h('button',
{
onClick(event) {
alert('Click');
}
},
'Click Me!'
)
}
}
const App = {
components: {
myComponent1, myComponent2, myComponent3
}
}
const app = createApp(App)
app.mount('#app')
<div id="app">
My Component 1: <my-component1></my-component1><br/>
My Component 2: <my-component2></my-component2><br/>
My Component 3: <my-component3></my-component3><br/>
</div>
<script src="https://unpkg.com/vue#3/dist/vue.global.prod.js"></script>
<script type="text/x-template" id="my-component">
<div class="test">
{{ testFunction( param1 ) }}
</div>
</script>
Related
I have two child components I have to pass dynamically props from first child to parent and from parent to second child.
Parent
<script>
data: () => ({
model: {}
}),
methods: {
changeData(payload) {
this.model.personalData = {...payload}
}
}
</script>
<template>
<first-child #changeData="(payload) => changeData(payload)"/>
<second-child :enter-object="model" />
</template>
Child one
<script>
data: () => ({
model: {}
}),
methods: {
changeData() {
this.$emit("changeData", this.model);
}
}
</script>
<template>
<v-text-field v-model="model.name" #input="changeData()">
<v-text-field v-model="model.email" #input="changeData()">
</template>
Child two
<script>
props: {
enterObject: {
type: Object,
required: false,
default: () => ({})
}
},
data: () => ({
model: {}
}),
watch: {
enterObject: {
immediate: true,
handler() {
Object.assign(this.model.personalData, this.enterObject.personalData);
}
}
</script>
<template>
<div>
<div v-if="model.personalData.name || model.personalData.email">
<span class="mr-3">{{ model.personalData.name }}</span>
<span>{{ model.personalData.email }}</span>
</div>
<div v-else>
No data
</div>
</div>
</template>
I get data in parent component with no problem, but this data doesn't pass to second child, why I have always "No data" ?
I tested your code and found a few things:
You need to create "personalData" inside the model in "childTwo".
<template>
<div>
// I changed the validation for personalData
<div v-if="model.personalData">
<span class="mr-3">{{ model.personalData.name }}</span>
<span>{{ model.personalData.email }}</span>
</div>
<div v-else>No data</div>
</div>
</template>
export default {
props: {
enterObject: {
type: Object,
required: false,
default: () => ({})
}
},
data: () => ({
model: {
personalData: {}
}
}),
watch: {
enterObject: {
deep: true,
handler() {
// Add a validation in the handler, you can use Object assign inside the validation.
if(this.enterObject) {
Object.assign(this.model.personalData, this.enterObject.personalData)
}
}
}
}
It's worked for me.I hope it helps you.
You have to assign the value of the object using this.$set for more about object reactivity click here
your Parent component should be like this:-
here is the working example
<template>
<div>
<first-child #change-data="(payload) => changeData(payload)" />
<second-child :enter-object="model" />
</div>
</template>
<script>
import FirstChild from "./FirstChild";
import SecondChild from "./SecondChild";
export default {
data: () => ({
model: {},
compKey: 0,
}),
components: {
FirstChild,
SecondChild,
},
methods: {
changeData(payload) {
this.$set(this.model, "test", payload);
//this.model.test = payload;
},
},
};
</script>
I would like to transform the span into a real element. When I try this way the appendChild gives me an error because the variable is a string and not and object. Any ideas?
export default{
data(){
....
}
methods:{
update_period: function(event){
var start = moment(event.start).format('M/D/Y'),
end = moment(event.end).format('M/D/Y');
var span = `<span #click="remove">{{ start }} - {{ end }}</span>`
this.$refs.spans.appendChild(span);
},
remove: function(event){
event.target.remove()
}
}
}
<div ref="spans">
</div>
You can get the same result in this way:
<template>
<div>
<span #click="remove" v-if="period">{{ period }}</span>
</div>
</template>
<script>
export default {
data() {
return {
period: null,
}
},
methods:{
update_period(event) {
this.period = moment(event.start).format('M/D/Y') + ' - ' + moment(event.end).format('M/D/Y')
},
remove() {
this.period = null;
}
}
}
</script>
I have a component “MText”,the main code is as follows :
<template>
<vue-draggable-resizable #click="deleteFun">
</vue-draggable-resizable>
</template>
export default {
method:{
deleteFun () {
this.$el.remove();
}
}}
and in another file,I have a function like this
function createText(){
let MyComponent =Vue.extend({
template:"<MText></MText>",
components:{MText},
data () {
return {}
}})
return new MyComponent(); }
and I have a button,click event bind a function “addText”,like this
addText(){
let text = createText();
let panel = document.getElementById("palette");
let tp_dom = document.createElement("div");
tp_dom.setAttribute("id","id");
panel.appendChild(tp_dom);
text.$mount(tp_dom);
}
the quesition is that when I run “addText” twice, the dom “#palette”
have two “MText” elements,then,I click the second “MText” element,why
the first “MText” is deleted;“this.$el” always reference the first
“MText”
I have no idea what your problem is, but here's a working example:
https://jsfiddle.net/oddswe36/
let i = 0;
// Register your component globally
Vue.component('MText', {
template: `
<div #click="removeMe">click to remove me {{ counter }}</div>
`,
data() {
return {
counter: i++
}
},
methods: {
removeMe() {
this.$el.remove()
}
}
})
function createText() {
const MyComponent = Vue.extend({
template:"<MText></MText>",
})
return new MyComponent();
}
function addText() {
const text = createText();
const panel = document.getElementById("palette");
const tp_dom = document.createElement("div");
tp_dom.setAttribute("id","id");
panel.appendChild(tp_dom);
text.$mount(tp_dom);
};
addText();
addText();
addText();
addText();
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id="palette"></div>
I have this 3 components in VueJS. The problem i want to solve is: When i click at vehicle component, it needs to be selected (selected = true) and other vehicles unselected.
What i need to do for two-way data binding? Because i'm changing this selected property in VehiclesList.vue component and it also need to be changed in Monit.vue (which is a parent) and 'Vehicle.vue' need to watch this property for change class.
Also problem is with updating vehicles. In Monit.vue i do not update full object like this.vehicles = response.vehicles, but i do each by each one, and changing only monit property.
Maybe easier would be use a store for this. But i want to do this in components.
EDITED:Data sctructure
{
"m":[
{
"id":"v19",
"regno":"ATECH DOBLO",
"dt":"2017-10-09 13:19:01",
"lon":17.96442604,
"lat":50.66988373,
"v":0,
"th":0,
"r":0,
"g":28,
"s":"3",
"pow":1
},
{
"id":"v20",
"regno":"ATECH DUCATO_2",
"dt":"2017-10-10 01:00:03",
"lon":17.96442604,
"lat":50.6698494,
"v":0,
"th":0,
"r":0,
"g":20,
"s":"3"
},
]
}
Monit.vue
<template>
<div class="module-container">
<div class="module-container-widgets">
<vehicles-list :vehicles="vehicles"></vehicles-list>
</div>
</div>
</template>
<script>
import VehiclesList from '#/components/modules/monit/VehiclesList.vue';
export default {
name: "Monit",
data (){
return {
vehicles: null
}
},
components: {
VehiclesList
},
methods: {
getMonitData(opt){
let self = this;
if (this.getMonitDataTimer) clearTimeout(this.getMonitDataTimer);
this.axios({
url:'/monit',
})
.then(res => {
let data = res.data;
console.log(data);
if (!data.err){
self.updateVehicles(data.m);
}
self.getMonitDataTimer = setTimeout(()=>{
self.getMonitData();
}, self.getMonitDataDelay);
})
.catch(error => {
})
},
updateVehicles(data){
let self = this;
if (!this.vehicles){
this.vehicles = {};
data.forEach((v,id) => {
self.vehicles[v.id] = {
monit: v,
no: Object.keys(self.vehicles).length + 1
}
});
} else {
data.forEach((v,id) => {
if (self.vehicles[v.id]) {
self.vehicles[v.id].monit = v;
} else {
self.vehicles[v.id] = {
monit: v,
no: Object.keys(self.vehicles).length + 1
}
}
});
}
},
},
mounted: function(){
this.getMonitData();
}
};
</script>
VehiclesList.vue
<template>
<div class="vehicles-list" :class="{'vehicles-list--short': isShort}">
<ul>
<vehicle
v-for="v in vehicles"
:key="v.id"
:data="v"
#click.native="select(v)"
></vehicle>
</ul>
</div>
</template>
<script>
import Vehicle from '#/components/modules/monit/VehiclesListItem.vue';
export default {
data: function(){
return {
isShort: true
}
},
props:{
vehicles: {}
},
methods:{
select(vehicle){
let id = vehicle.monit.id;
console.log("Select vehicle: " + id);
_.forEach((v, id) => {
v.selected = false;
});
this.vehicles[id].selected = true;
}
},
components:{
Vehicle
}
}
</script>
Vehicle.vue
<template>
<li class="vehicle" :id="data.id" :class="classes">
<div class="vehicle-info">
<div class="vehicle-info--regno font-weight-bold"><span class="vehicle-info--no">{{data.no}}.</span> {{ data.monit.regno }}</div>
</div>
<div class="vehicle-stats">
<div v-if="data.monit.v !== 'undefined'" class="vehicle-stat--speed" data-name="speed"><i class="mdi mdi-speedometer"></i>{{ data.monit.v }} km/h</div>
</div>
</li>
</template>
<script>
export default {
props:{
data: Object
},
computed:{
classes (){
return {
'vehicle--selected': this.data.selected
}
}
}
}
</script>
Two-way component data binding was deprecated in VueJS 2.0 for a more event-driven model: https://v2.vuejs.org/v2/guide/components.html#One-Way-Data-Flow
This means, that changes made in the parent are still propagated to the child component (one-way). Changes you make inside the child component need to be explicitly send back to the parent via custom events: https://v2.vuejs.org/v2/guide/components.html#Custom-Events or in 2.3.0+ the sync keyword: https://v2.vuejs.org/v2/guide/components.html#sync-Modifier
EDIT Alternative (maybe better) approach:
Monit.vue:
<template>
<div class="module-container">
<div class="module-container-widgets">
<vehicles-list :vehicles="vehicles" v-on:vehicleSelected="onVehicleSelected"></vehicles-list>
</div>
</div>
</template>
<script>
import VehiclesList from '#/components/modules/monit/VehiclesList.vue';
export default {
name: "Monit",
data (){
return {
vehicles: null
}
},
components: {
VehiclesList
},
methods: {
onVehicleSelected: function (id) {
_.forEach((v, id) => {
v.selected = false;
});
this.vehicles[id].selected = true;
}
...other methods
},
mounted: function(){
this.getMonitData();
}
};
</script>
VehicleList.vue:
methods:{
select(vehicle){
this.$emit('vehicleSelected', vehicle.monit.id)
}
},
Original post:
For your example this would probably mean that you need to emit changes inside the select method and you need to use some sort of mutable object inside the VehicleList.vue:
export default {
data: function(){
return {
isShort: true,
mutableVehicles: {}
}
},
props:{
vehicles: {}
},
methods:{
select(vehicle){
let id = vehicle.monit.id;
console.log("Select vehicle: " + id);
_.forEach((v, id) => {
v.selected = false;
});
this.mutableVehicles[id].selected = true;
this.$emit('update:vehicles', this.mutableVehicles);
},
vehilcesLoaded () {
// Call this function from the parent once the data was loaded from the api.
// This ensures that we don't overwrite the child data with data from the parent when something changes.
// But still have the up-to-date data from the api
this.mutableVehilces = this.vehicles
}
},
components:{
Vehicle
}
}
Monit.vue
<template>
<div class="module-container">
<div class="module-container-widgets">
<vehicles-list :vehicles.sync="vehicles"></vehicles-list>
</div>
</div>
</template>
<script>
You still should maybe think more about responsibilities. Shouldn't the VehicleList.vue component be responsible for loading and managing the vehicles? This probably would make thinks a bit easier.
EDIT 2:
Try to $set the inner object and see if this helps:
self.$set(self.vehicles, v.id, {
monit: v,
no: Object.keys(self.vehicles).length + 1,
selected: false
});
I am trying to click() a bound checkbox in Vue.js 2. I want to click a particular dynamic checkbox in the mounted() lifecycle event, without jQuery.
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
<div ref='users' v-for="user in users">
<input type='checkbox'
:ref='user.username'
:id='user.id'
:value='user.username' />
<label :for='user.id'>{{ user.name }} [username: {{ user.username }}]</label>
</div>
<div #click="trigger" class="trigger">Click me</div>
</div>
<script>
new Vue({
el: '#app',
data: {
users: ''
},
methods: {
popUsers: function() {
axios.get('https://jsonplaceholder.typicode.com/users').then(res => {
this.users = res.data;
});
},
trigger() {
console.log(this.$refs);
this.$refs.Karianne[0].click();//works
}
},
created: function () {
this.popUsers();
},
mounted: function () {
console.log(this.$refs);
this.$refs.Karianne[0].click(); //doesn't work. i want to "click Karianne" when everything is loaded.
}
})
</script>
Here is my jsfiddle: https://jsfiddle.net/zippyferguson/we8Latcw/21/
this.$refs.Karianne[0].click(); works when you click "Click me", but not in on mounted. Too early?
new Vue({
el: '#app',
data: {
users: ''
},
methods: {
popUsers: function() {
let self = this;
axios.get('https://jsonplaceholder.typicode.com/users').then(res => {
this.users = res.data;
self.$nextTick(function() {
self.$refs.Karianne[0].click() //works
})
});
}
},
created: function () {
this.popUsers();
},
mounted: function () {
let self = this;
self.$nextTick(function() {
self.$refs.Karianne[0].click() //doesn't work
})
}
})
Try doing it like this.
mounted() {
Vue.nextTick(() => {
this.$refs.Karianne[0].click()
})
}
I think that for some reason $refs is still empty at the moment of mounting the vue component. If Vue.nextTick doesn't help, try doing it inside a timeout callback.
mounted() {
setTimeout(() => {
this.$refs.Karianne[0].click()
}, 200)
}