How can I get data from another Vue file? - html

As the code show below, A.vue file has element data return some number values
<template></template>
<script>
export default {
data(){
return{
element: [
{
number:'11'
}
{
number:'22'
}
]
}
}
}
</script>
Now I want to get element.length from A.vue to B.vue. Is there a way to do that? I saw a solution with button click but i dont want to use button to pass data.
B.vue file
<template>
<div>I want to get element.length here</div>
</template>

You can simply achieve it by passing prop (which contains the length of the element array) from A.vue component to B.vue component. Here is the live demo :
Vue.component('bcomponent', {
// declare the props
props: ['length'],
// just like data, the prop can be used inside templates
// and is also made available in the vm as this.message
template: '<div>Element length: {{ length }}</div>',
});
var app = new Vue({
el: '#app',
data: {
element: [{
number: '11'
}, {
number: '22'
}]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!-- Component A -->
<div id="app">
<BComponent :length="element.length">
</BComponent>
</div>

If it's possible, just pass the data as a prop from B to A, this way you can implement any logic on the data.
If it's not, you should use vuex for data storage, so any component can access it.

Related

How to include inline .svg in Nuxt application

I want to do a common thing - include dynamically an svg HTML in Vue Nuxt application which I will able to style. To do this, I created a component but instead of image, I get a text data:image/svg+xhtml....
How to make it work?
<template>
<div v-html="src"></div>
</template>
<script>
export default {
name: 'Icon',
props: {
name: {
type: String,
required: true
}
},
computed: {
src() {
const src = require(`assets/icons/${this.name}.svg`)
return src
}
}
}
</script>
It seems like #nuxtjs/svg will do what you're trying to do. After installing it, try:
<template>
<div v-html="src"></div>
</template>
<script>
export default {
name: 'Icon',
props: {
name: {
type: String,
required: true
}
},
computed: {
src() {
const src = require(`assets/icons/${this.name}.svg?raw`)
return src
}
}
}
</script>
It's not easy and I tried a bunch of different solutions that "seemed" like they should work.
My understanding is that it comes down to how Webpack deals with "image" assets and using them inline vs stand-alone sort of changes the definition.
I've got a library of SVG icons that needed code access (eg change colors after run time) so I had to have the SVG inline. Here's where I landed, It's not ideal but it works.
Create a new component with a prop slot for SVG name. Inside that component add all your svg's as code. Wrap each in a v-if.
<template>
<div class="svgIcon">
<svg v-if="icon == 'name1'">...</svg>
<svg v-if="icon == 'name2'">...</svg>
<svg v-if="icon == 'name3'">...</svg>
<svg v-if="icon == 'name4'">...</svg>
</div>
</template>
<script>
export default {
props: ['icon']
}
</script>
Then use the component by filling the name you want in the slot
<template>
<div>
<svgIcons :icon="name1"></svgIcons>
</div>
</template>
<script>
import svgIcons from '../path/to/iconsComponent.vue'
export default {
components: { svgIcons },
...
}
</script>

How to dynamically append HTML element to component in Vue.js

I'm new to vue.js, before this i'm using jquery or js for my project, i'm working on a project that require me to append HTML element dynamically on button click, and at the same time bind the input value to model, similar to:
$(".button").click(function() {
$("#target").append("<input type='hidden' name='data' v-model='inputModel' value='1'/>");
});
But i need this in Vue.js ways.
Here is my code:
data() {
return {
programmeBanner: [],
dropzoneOptions: {
...
...
init: function () {
this.on("success", function(file, response) {
file.previewElement.id = response;
// this is the part that i want to append the html input into
// the .dz-preview is the target that i want to append
$(".dz-preview[id='"+response+"']").append("<input type='hidden' name='"+fileInputName+"[]' v-model='programmeBanner' class='"+fileInputName+"' value='"+response+"'/>");
});
},
...
Here is a sample that i want to achieve, this is in Jquery, i need it in Vue.js
https://jsfiddle.net/041xnfzu/
Hmm I think you're mixing all kinds of code here :)
First off, you shouldn't use jquery inside VueJS. I think that your setup is a little off. You shouldn't define a whole object with functions and event listeners in your vue data object.
That's what Vue components are for, define methods in your methods property and data in you data property.
Thanks to your jsfiddle example, I have this pure vuejs example for you on codepen: https://codepen.io/bergur/pen/vwRJVx
VueJS code:
new Vue({
el: '#demo',
name: 'Adding html',
data() {
return {
inputs: []
}
},
methods: {
addInput() {
this.inputs.push(this.inputs.length+1)
}
},
computed: {
buttonText() {
return this.showInput ? 'Hide input' : 'Show input'
}
}
})
HTML template
<div id="demo">
<button #click="addInput">Add input</button>
<div v-for="(input, index) in inputs">
<input name="data" v-model="inputs[index]" />
</div>
<p>
First value: {{ inputs[0] }}<br />
Second value: {{ inputs[1] }}
</p>
</div>
Here's a walkthrough of the code.
We create a data property called inputs, that is an array.
We create a method called addInput and all that does is to push a new item into the inputs array
In the template we loop with v-for through our inputs array and render a input for each item in our inputs data property.
We then use v-model to bind each input to its corresponding place in the inputs array.
You can try to change the input value and see that the template updates the value.
So input[0] holds the value for the first input, input[1] holds the value for the second input and so on.
If you want only one element to be appended to component, then you should use v-if
https://v2.vuejs.org/v2/guide/conditional.html#v-if
If you want to append multiple elements, like todo list, you should use v-for
https://v2.vuejs.org/v2/guide/#Conditionals-and-Loops

Function arguments and parameters not working in vuetify project using "this" keyword?

I am trying to accomplish something in a vuetify project like the example below, which works with plain html/javascript:
<body>
<button id="anid" onclick="idcheck(this.id)">
</button
</body>
<script>
function idcheck(id){
console.log(id);
}
</script>
But in my vuetify project when I try to accomplish the same kind of thing as seen below, I get a console error of "Cannot read property 'id' of null":
<v-btn id="price" flat small #click="idcheck(this.id)">Price</v-btn>
methods: {
idcheck(id){
alert(id);
}
Is there a way to get the id of the .v-btn element with this sort of method or is this not possible in a vuetify project?
Edit: The problem was from me having two functions placed in the button #click, which I unwisely did not state in my example. The accepted answer works.
Is there a way to get the id of the .v-btn element with this sort of method...
There is, but I wonder what you intend to do with it when you could readily access the object itself (the button) by reference.
<v-btn id="price" flat small #click="idcheck">Price</v-btn>
{
// ...
methods: {
idcheck(e) {
const button = e.target;
const id = button.id; // price
// ...
}
}
}
You can save the id in data:
<v-btn :id="btnId" flat small #click="idcheck(btnId)">Price</v-btn>
<script>
export default {
data:()=>{
btnId:'price'
},
methods: {
idcheck(id){
alert(id);
}
}
</script>

Two way data binding with Polymer.Templatizer

I am trying to get two way data-binding between a host element and a template in Polymer using templatizer. For example if I am trying to keep two input boxes in-sync:
<html>
<body>
<my-element>
<template >
<input type="text" value="{{test::change}}" />
<div>The value of 'test' is: <span>{{test}}</span></div>
</template>
</my-element>
<dom-module id="my-element">
<template>
<input type="text" value="{{test::change}}" />
value:
<p>{{test}}</p>
<div id="items"></div>
<content id="template"></content>
</template>
</dom-module>
<script>
Polymer({
is: 'my-element',
test: {
type: String,
value: "a"
},
behaviors: [ Polymer.Templatizer ],
_forwardParentProp: function(prop, value) {debugger},
_forwardParentPath: function(path, value) {debugger},
_forwardInstanceProp: function(inst, prop, value) {debugger},
_forwardInstancePath: function(inst, path, value) {debugger},
ready: function() {
this._instanceProps = {
test: true
};
var templates = Polymer.dom(this.$.template).getDistributedNodes();
template = templates[1];
this.templatize(template);
var itemNode = this.stamp({ test: this.test});
Polymer.dom(this.$.items).appendChild(itemNode.root);
}
});
</script>
</body>
</html>
In the above code I hit the debugger in the _forwardInstanceProp but not any of the others. Why is this? Inside _forwardInstanceProp I can access my-element and manually update the test property. Is there a better way to do this? I also could add an observer on my-element to the test property and then propagate any changes in my-element to the template. Is there a better way to do that? I am just trying to understand what all four of these methods do and when/why they should be used.
It beats my why I can never get neither _forwardParentPath nor _forwardParentProp to run. However, I know when the other two run :)
_forwardInstanceProp runs for direct properties of model passed to stamp and _instanceProps is initialized:
this._instanceProps = {
text: true
};
var clone = this.stamp({
text: this.text
});
_forwardInstancePath on the other hand runs when you pass nested objects to stamp:
var clone = this.stamp({
nested: {
text: this.text
}
});
See this bin for an example: http://jsbin.com/kipato/2/edit?html,js,console,output
In the stamped template there are two inputs bound to two variables which trigger instanceProp and instancePath. Unfortunately I've been unable to fix the error thrown when the latter happens.

Repeat light dom element

In my component I would like to repeat a list of item with template provided by the light dom of the component. For example:
<template is="dom-repeat" items="{{items}}">
<content select="#itemTemplate"></content>
</template>
However, it seems that Polymer only inserts the light dom element #itemTemplate exactly one time instead of multiple times. Is there other way to repeat a light dom element?
I have created a simple prototype, that lets you specify the number of repetitions of the light DOM template.
Because the content is in the light DOM, you can style it from the outside as you would usually do. And data binding inside the template also works, since I have implemented the _forwardParentProp, and _forwardParentPath methods from the Templatizer.
Be aware, that I have not implemented the instance specific properties, which would allow per row specific variables, such as index and item. This can, of course, be done, but would need a bit more work.
See the prototype in action: JSBin.
OK, let's go into details:
The usage of the test-element along with data-binding to both input elements is fairly straightforward:
<template is="dom-bind">
Number of repeats: <input type="text" value="{{repeats::input}}" /> <br />
Custom message: <input type="text" value="{{customMessage::input}}" />
<test-element repeats="{{repeats}}">
<template>
<h1>Title!</h1>
<p>
Custom message: <em>[[customMessage]]</em>
</p>
</template>
</test-element>
</template>
Notice the dom-bind, which is needed to create a data-binding scope.
As for the test-element, the whole source code looks like this:
<dom-module id="test-element">
<template>
<style>
:host {
display: block;
}
</style>
<content></content>
</template>
<script>
Polymer({
is: 'test-element',
behaviors: [
Polymer.Templatizer,
],
properties: {
repeats: {
type: Number,
value: 3,
notify: true,
},
},
observers: [
'_repeatsChanged(repeats)',
],
_repeatsChanged: function(repeats) {
// First time only: initialize template
if (this.template === undefined) {
this.template = Polymer.dom(this).querySelector('template');
this.templatize(this.template);
}
// Remove previously stamped children
while (Polymer.dom(this).firstChild) {
Polymer.dom(this).removeChild(Polymer.dom(this).firstChild);
}
// Stamp new ones
this.stamped = new Array(repeats);
var inst;
for (var i = 0; i < repeats; i++) {
inst = this.stamp(null);
this.stamped[i] = inst.root.querySelector('*');
Polymer.dom(this).appendChild(inst.root);
}
},
// Copied from iron-list
_forwardParentProp: function(prop, value) {
if (this.stamped) {
this.stamped.forEach(function(item) {
item._templateInstance[prop] = value;
}, this);
}
},
// Copied from iron-list
_forwardParentPath: function(path, value) {
if (this.stamped) {
this.stamped.forEach(function(item) {
item._templateInstance.notifyPath(path, value, true);
}, this);
}
},
});
</script>
</dom-module>
There is only one property, repeats, which specifies the number of stamped instances. Default value is 3. To accomodate changes of said property's value, a observer has been created. This is also the place where the stamping takes place:
_repeatsChanged: function(repeats) {
// First time only: initialize template
if (this.template === undefined) {
this.template = Polymer.dom(this).querySelector('template');
this.templatize(this.template);
}
// Remove previously stamped children
while (Polymer.dom(this).firstChild) {
Polymer.dom(this).removeChild(Polymer.dom(this).firstChild);
}
// Stamp new ones
this.stamped = new Array(repeats);
var inst;
for (var i = 0; i < repeats; i++) {
inst = this.stamp(null);
this.stamped[i] = inst.root.querySelector('*');
Polymer.dom(this).appendChild(inst.root);
}
},
Firstly (and only once), the template is read from the light DOM and
the templatize method is called. This method initializes the
Templatize behavior.
Secondly, all previously stamped children are removed (so that the
elements don't just build up infinitely).
Thirdly, new children are stamped, according to the current value of
repeats. All stamped instances are saved to this.stamped, which
is needed for the data-binding from the outside to work.
Last but not least, the Templatizer behavior is implemented via two methods (and two are left unimplemented):
// Copied from iron-list
_forwardParentProp: function(prop, value) {
if (this.stamped) {
this.stamped.forEach(function(item) {
item._templateInstance[prop] = value;
}, this);
}
},
// Copied from iron-list
_forwardParentPath: function(path, value) {
if (this.stamped) {
this.stamped.forEach(function(item) {
item._templateInstance.notifyPath(path, value, true);
}, this);
}
},
Both methods are taken from the iron-list. They iterate through the stamped children and propagate property changes and path notifications.
You can include your content in a separate element and use it.
<template is="dom-repeat" items={{items}}">
<child-element item=[[item]]></child-element>
</template>